Initial commit

0.2.0
Raylin51 2019-12-04 18:13:03 +08:00
commit 4a70313034
195 changed files with 30484 additions and 0 deletions

2
.env Normal file
View File

@ -0,0 +1,2 @@
PUBLIC_URL=./
EXTENSION_ENV=development

6
.gitignore vendored Normal file
View File

@ -0,0 +1,6 @@
build
node_modules/
.vscode-test/
*.vsix
dist
.DS_Store

7
.vscode/extensions.json vendored Normal file
View File

@ -0,0 +1,7 @@
{
// See http://go.microsoft.com/fwlink/?LinkId=827846
// for the documentation about the extensions.json format
"recommendations": [
"ms-vscode.vscode-typescript-tslint-plugin"
]
}

66
.vscode/launch.json vendored Normal file
View File

@ -0,0 +1,66 @@
// A launch configuration that compiles the extension and then opens it inside a new window
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
{
"version": "0.2.0",
"configurations": [
{
"name": "Extension",
"type": "extensionHost",
"request": "launch",
"runtimeExecutable": "${execPath}",
"args": [
"--extensionDevelopmentPath=${workspaceFolder}"
],
"outFiles": [
"${workspaceFolder}/build/**/*.js"
],
"preLaunchTask": "npm: webpack-dev"
},
{
"name": "Server",
"type": "node",
"request": "launch",
"cwd": "${workspaceFolder}",
"program": "${workspaceFolder}/src/debugadapter.ts",
"args": [
"--server=4711"
],
"outFiles": [
"${workspaceFolder}/build/**/*.js"
]
},
{
"name": "Views",
"type": "node",
"request": "attach",
"preLaunchTask": "npm: watch",
"stopOnEntry": false
},
{
"name": "Extension Tests",
"type": "extensionHost",
"request": "launch",
"runtimeExecutable": "${execPath}",
"args": [
"--extensionDevelopmentPath=${workspaceFolder}",
"--extensionTestsPath=${workspaceFolder}/out/test/suite/index"
],
"outFiles": [
"${workspaceFolder}/build/test/**/*.js"
],
"preLaunchTask": "npm: watch"
}
],
"compounds": [
{
"name": "Extension + Server",
"configurations": ["Extension", "Server"]
},
{
"name": "Extension + Views",
"configurations": ["Extension", "Views"]
}
]
}

11
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,11 @@
// Place your settings in this file to overwrite default and user settings.
{
"files.exclude": {
"out": false // set this to true to hide the "out" folder with the compiled JS files
},
"search.exclude": {
"out": true // set this to false to include "out" folder in search results
},
// Turn off tsc task auto detection since we have the necessary tasks as npm scripts
"typescript.tsc.autoDetect": "off"
}

44
.vscode/tasks.json vendored Normal file
View File

@ -0,0 +1,44 @@
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
{
"version": "2.0.0",
"tasks": [
{
"type": "npm",
"script": "webpack-dev",
"problemMatcher": {
"owner": "Webpack (Dev, Continuous)",
"severity": "error",
"fileLocation": "absolute",
"source": "webpack-typescript",
"background": {
"activeOnStart": true,
"beginsPattern": "webpack is watching the files…",
"endsPattern": "Time: (\\d+)ms"
},
"pattern": [
{
"regexp": "ERROR in ([^\\(]*)\\((\\d+),(\\d+)\\):",
"file": 1,
"line": 2,
"column": 3
},
{
"regexp": "([A-Za-z0-9-]+):(.*)",
"message": 2,
"code": 1
}
]
},
"isBackground": true,
"presentation": {
"reveal": "never"
},
"group": {
"kind": "build",
"isDefault": true
}
}
]
}

29
.vscodeignore Normal file
View File

@ -0,0 +1,29 @@
**/*.ts
**/tsconfig.json
**/tslint.json
.DS_Store
src/
view-src/
.env
config/
.vscode/
scripts/
public/
.gitignore
node_modules/
webpack.config.js
!node_modules/serialport/
!node_modules/@serialport/
!node_modules/debug
!node_modules/ms
!node_modules/bindings
!node_modules/file-uri-to-path
!node_modules/7zip-bin
!node_modules/7zip-bin-wrapper
!node_modules/source-map-support
!node_modules/split2
!node_modules/iconv-lite
!node_modules/buffer-from
!node_modules/safer-buffer
!node_modules/inherits
!node_modules/util-deprecate

5
CHANGELOG.md Normal file
View File

@ -0,0 +1,5 @@
# Change Log
## 0.1.0
- Initial preview release

201
LICENSE Normal file
View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

156
README.md Normal file
View File

@ -0,0 +1,156 @@
# Kendryte Dev Tool for Visual Studio Code
[English](./README_EN.md)
- [使用准备](#使用准备)
- [快速开始](#快速开始)
- [项目结构](#项目结构)
- [界面功能介绍](#界面功能介绍)
- [常见问题](#常见问题)
- [Windows](#Windows)
- [MacOS](#MacOS)
- [Linux](#Linux)
## 使用准备
首先安装 [VSCode](https://code.visualstudio.com/)。安装完毕后在 VSCode Extension 中搜索 Kendryte 即可快速安装本插件。本插件目前仅支持 Kendryte 官方开发板 KD233。
### MacOS 环境准备
1.安装 Homebrew
``` bash
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
```
2.安装所需依赖
``` bash
brew install libusb mpfr
```
### Linux 环境准备
#### 依赖安装
Linux 用户在使用之前需要安装 libftdi-dev libhidapi-dev libusb 。
``` bash
sudo apt install libftdi-dev libhidapi-dev libusb-dev
```
或者
``` bash
sudo yum install libftdi hidapi libusb
```
#### 配置调试器权限
1.下载 [60-openocd.rules](https://mirrors-kendryte.s3.cn-northwest-1.amazonaws.com.cn/60-openocd.rules) 文件并将文件放入 `/etc/udev/rules.d`
2.重载 udev
``` bash
sudo udevadm control --reload
```
3.添加用户到 plugdev 用户组
``` bash
sudo usermod -aG plugdev $USER
```
## 快速开始
1.启动插件后Kendryte 控制台会自动弹出,点击 Examples 切换至示例项目商店。
![image](./resources/readme/quick-start/quick-1.jpeg)
2.选择一个项目下载至本地并打开。
![image](./resources/readme/quick-start/quick-2.jpeg)
3.点击状态栏中的编译并上传将项目通过串口烧写至开发板。
![image](./resources/readme/quick-start/quick-3.jpeg)
4.在开发板上查看效果。
## 项目结构
``` Bash
.
├── .vscode
├── CMakeLists.txt
├── README.md
├── build
│   ├── CMakeCache.txt
│   ├── CMakeFiles
│   ├── Makefile
│   ├── ai_image
│   ├── camera-standalone-driver
│   ├── cmake_install.cmake
│   ├── compile_commands.json
│   ├── ${Project-name}
│   ├── ${Project-name}.bin
│   ├── lcd-nt35310-standalone-driver
│   ├── standalone-sdk
│   └── w25qxx-standalone-driver
├── config
│   ├── device-manager.json
│   ├── flash-manager.h
│   ├── flash-manager.json
│   ├── fpioa-config.c
│   ├── fpioa-config.h
│   └── ide-hook-main.c
├── detect.kmodel
├── kendryte-package.json
├── kendryte_libraries
│   ├── ai_image
│   ├── camera-standalone-driver
│   ├── lcd-nt35310-standalone-driver
│   ├── standalone-sdk
│   └── w25qxx-standalone-driver
└──  src
  └── main.c
```
- .vscode: 该目录中内容为自动生成,包含了调试选项,编译命令以及一系列插件直接使用的配置文件。
- CMakeLists.txt: 该文件为插件编译时自动生成的 CMakelists 文件
- build: 该目录中内容为编译产物,其中 ${Project-name} 以及 ${Project-name}.bin 为编译出的最终文件。
- config: 该目录中包含开发板中的引脚配置,模型地址分配配置,内容可修改。
- detect.kmodel: Kendryte 专属模型文件。
- kendryte-package.json: 项目配置文件包含项目名source 文件等基本信息,可修改。
- kendryte_libraries: 该目录为依赖安装目录,所有的依赖都会安装到该目录下,安装后的依赖库可以直接调用,无需再手动配置 include。正常情况下不应该修改该目录中文件。
- src: 项目源码目录。
## 界面功能介绍
![image](./resources/readme/full-screen.png)
![image](./resources/readme/status-bar.png)
![image](./resources/readme/kendryte-index.png)
![image](./resources/readme/kendryte-lib.png)
## 常见问题
### Windows
1. Q: 为什么调试时启动 Openocd 报错 libusb_error_not_supported
A: 请下载[Zadig](https://zadig.akeo.ie/)将 JLink 驱动转为 Libusb。
### MacOS
### Linux
1. Q: 为什么调试启动 Openocd 报错 libusb_error_access
A: 请根据上文[配置调试器权限](#配置调试器权限)来获取调试器权限并重新接入调试设备。如果问题仍未解决,请在 issue 中联系我们。
2. Q: 为什么烧写时需要 sudo 权限密码?
A: 只有当前用户没有读取串口设备权限时才会出现需要密码,您也可以自行配置串口设备权限组。

150
README_EN.md Normal file
View File

@ -0,0 +1,150 @@
# Kendryte Dev Tool for Visual Studio Code
[中文版](./README.md)
- [Prepare](#Prepare)
- [Quick Start](#Quick\ Start)
- [Directory Structure](#Directory\ Structure)
- [Features](#Features)
- [Questions](#Questions)
- [Windows](#Windows)
- [MacOS](#MacOS)
- [Linux](#Linux)
## Prepare
Install [VSCode](https://code.visualstudio.com/) on your computer. Search `Kendryte` on VSCode Extension Market and install. This development tool only support `Kendryte KD233` board for now.
### MacOS environment
1.Install Homebrew
``` bash
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
```
2.Install dependencies
``` bash
brew install libusb mpfr
```
### Linux environment
#### Install dependencies
``` bash
sudo apt install libftdi-dev libhidapi-dev libusb-dev
```
or
``` bash
sudo yum install libftdi hidapi libusb
```
#### Debugger permission
1.Download [60-openocd.rules](https://mirrors-kendryte.s3.cn-northwest-1.amazonaws.com.cn/60-openocd.rules) and put it on `/etc/udev/rules.d`
2.Reload `udev`
``` bash
sudo udevadm control --reload
```
3.Add user to `plugdev` group
``` bash
sudo usermod -aG plugdev $USER
```
## Quick Start
1.Kendryte controller will open after installed, click `Examples` tag to switch to the examples store.
![image](./resources/readme/en/quick-start/quick-1.png)
2.Select an example and download.
![image](./resources/readme/en/quick-start/quick-2.png)
3.Click the `build and upload` button for build and upload to board.
![image](./resources/readme/en/quick-start/quick-3.png)
4.Check the board
## Directory Structure
``` Bash
.
├── .vscode
├── CMakeLists.txt
├── README.md
├── build
│   ├── CMakeCache.txt
│   ├── CMakeFiles
│   ├── Makefile
│   ├── ai_image
│   ├── camera-standalone-driver
│   ├── cmake_install.cmake
│   ├── compile_commands.json
│   ├── ${Project-name}
│   ├── ${Project-name}.bin
│   ├── lcd-nt35310-standalone-driver
│   ├── standalone-sdk
│   └── w25qxx-standalone-driver
├── config
│   ├── device-manager.json
│   ├── flash-manager.h
│   ├── flash-manager.json
│   ├── fpioa-config.c
│   ├── fpioa-config.h
│   └── ide-hook-main.c
├── detect.kmodel
├── kendryte-package.json
├── kendryte_libraries
│   ├── ai_image
│   ├── camera-standalone-driver
│   ├── lcd-nt35310-standalone-driver
│   ├── standalone-sdk
│   └── w25qxx-standalone-driver
└──  src
  └── main.c
```
- .vscode: The contents of this directory are automatically generated, include debug option, build commands and extension's config.
- CMakeLists.txt: This file is automatically generated when build.
- build: The contents of this directory are compiled product. The `${Project-name}.bin` and `${Project-name}` file are target file.
- config: The content of this directory include pin definitions and model address assignment. It can be overwrited.
- detect.kmodel: Kendryte model。
- kendryte-package.json: The config file of project. Include project name, source files and so on. It can be overwrited.
- kendryte_libraries: This directory is dependencies installation directory. All of dependencies will download on this directory. You shouldn't modify the contents of this directory most of the time.
- src: Source files.
## Features
![image](./resources/readme/en/full-screen.png)
![image](./resources/readme/en/status-bar.png)
## Questions
### Windows
1. Q: Openocd report error: libusb_error_not_supported?
A: Please download [Zadig](https://zadig.akeo.ie/) and switch `JLink` driver to `Libusb`
### MacOS
### Linux
1. Q: Openocd report error: libusb_error_access?
A: Please read [Debugger permission](#Debugger\ permission) to get the debugger permission and plug in device again. If you still have this problem, please contact us on issue.
2. Q: Why extension request sudo permission on upload?
A: If current don't have permission to read serialport device, it will request sudo permission. You can also config serialport devices permission by yourself.

7
config.json Normal file
View File

@ -0,0 +1,7 @@
{
"cdn": "http://kendryte-ide.s3-website.cn-northwest-1.amazonaws.com.cn/",
"third_party": "3rd-party/",
"package_version": "versions.json",
"host": "http://mirrors-kendryte.s3.cn-northwest-1.amazonaws.com.cn/",
"packages": "/package"
}

93
config/env.js Normal file
View File

@ -0,0 +1,93 @@
'use strict';
const fs = require('fs');
const path = require('path');
const paths = require('./paths');
// Make sure that including paths.js after env.js will read .env variables.
delete require.cache[require.resolve('./paths')];
const NODE_ENV = process.env.NODE_ENV;
if (!NODE_ENV) {
throw new Error(
'The NODE_ENV environment variable is required but was not specified.'
);
}
// https://github.com/bkeepers/dotenv#what-other-env-files-can-i-use
const dotenvFiles = [
`${paths.dotenv}.${NODE_ENV}.local`,
`${paths.dotenv}.${NODE_ENV}`,
// Don't include `.env.local` for `test` environment
// since normally you expect tests to produce the same
// results for everyone
NODE_ENV !== 'test' && `${paths.dotenv}.local`,
paths.dotenv,
].filter(Boolean);
// Load environment variables from .env* files. Suppress warnings using silent
// if this file is missing. dotenv will never modify any environment variables
// that have already been set. Variable expansion is supported in .env files.
// https://github.com/motdotla/dotenv
// https://github.com/motdotla/dotenv-expand
dotenvFiles.forEach(dotenvFile => {
if (fs.existsSync(dotenvFile)) {
require('dotenv-expand')(
require('dotenv').config({
path: dotenvFile,
})
);
}
});
// We support resolving modules according to `NODE_PATH`.
// This lets you use absolute paths in imports inside large monorepos:
// https://github.com/facebook/create-react-app/issues/253.
// It works similar to `NODE_PATH` in Node itself:
// https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders
// Note that unlike in Node, only *relative* paths from `NODE_PATH` are honored.
// Otherwise, we risk importing Node.js core modules into an app instead of Webpack shims.
// https://github.com/facebook/create-react-app/issues/1023#issuecomment-265344421
// We also resolve them to make sure all tools using them work consistently.
const appDirectory = fs.realpathSync(process.cwd());
process.env.NODE_PATH = (process.env.NODE_PATH || '')
.split(path.delimiter)
.filter(folder => folder && !path.isAbsolute(folder))
.map(folder => path.resolve(appDirectory, folder))
.join(path.delimiter);
// Grab NODE_ENV and REACT_APP_* environment variables and prepare them to be
// injected into the application via DefinePlugin in Webpack configuration.
const REACT_APP = /^REACT_APP_/i;
function getClientEnvironment(publicUrl) {
const raw = Object.keys(process.env)
.filter(key => REACT_APP.test(key))
.reduce(
(env, key) => {
env[key] = process.env[key];
return env;
},
{
// Useful for determining whether were running in production mode.
// Most importantly, it switches React into the correct mode.
NODE_ENV: process.env.NODE_ENV || 'development',
// Useful for resolving the correct path to static assets in `public`.
// For example, <img src={process.env.PUBLIC_URL + '/img/logo.png'} />.
// This should only be used as an escape hatch. Normally you would put
// images into the `src` and `import` them in code to get their paths.
PUBLIC_URL: publicUrl,
}
);
// Stringify all values so we can feed into Webpack DefinePlugin
const stringified = {
'process.env': Object.keys(raw).reduce((env, key) => {
env[key] = JSON.stringify(raw[key]);
return env;
}, {}),
};
return { raw, stringified };
}
module.exports = getClientEnvironment;

View File

@ -0,0 +1,14 @@
'use strict';
// This is a custom Jest transformer turning style imports into empty objects.
// http://facebook.github.io/jest/docs/en/webpack.html
module.exports = {
process() {
return 'module.exports = {};';
},
getCacheKey() {
// The output is always the same.
return 'cssTransform';
},
};

View File

@ -0,0 +1,40 @@
'use strict';
const path = require('path');
const camelcase = require('camelcase');
// This is a custom Jest transformer turning file imports into filenames.
// http://facebook.github.io/jest/docs/en/webpack.html
module.exports = {
process(src, filename) {
const assetFilename = JSON.stringify(path.basename(filename));
if (filename.match(/\.svg$/)) {
// Based on how SVGR generates a component name:
// https://github.com/smooth-code/svgr/blob/01b194cf967347d43d4cbe6b434404731b87cf27/packages/core/src/state.js#L6
const pascalCaseFilename = camelcase(path.parse(filename).name, {
pascalCase: true,
});
const componentName = `Svg${pascalCaseFilename}`;
return `const React = require('react');
module.exports = {
__esModule: true,
default: ${assetFilename},
ReactComponent: React.forwardRef(function ${componentName}(props, ref) {
return {
$$typeof: Symbol.for('react.element'),
type: 'svg',
ref: ref,
key: null,
props: Object.assign({}, props, {
children: ${assetFilename}
})
};
}),
};`;
}
return `module.exports = ${assetFilename};`;
},
};

141
config/modules.js Normal file
View File

@ -0,0 +1,141 @@
'use strict';
const fs = require('fs');
const path = require('path');
const paths = require('./paths');
const chalk = require('react-dev-utils/chalk');
const resolve = require('resolve');
/**
* Get additional module paths based on the baseUrl of a compilerOptions object.
*
* @param {Object} options
*/
function getAdditionalModulePaths(options = {}) {
const baseUrl = options.baseUrl;
// We need to explicitly check for null and undefined (and not a falsy value) because
// TypeScript treats an empty string as `.`.
if (baseUrl == null) {
// If there's no baseUrl set we respect NODE_PATH
// Note that NODE_PATH is deprecated and will be removed
// in the next major release of create-react-app.
const nodePath = process.env.NODE_PATH || '';
return nodePath.split(path.delimiter).filter(Boolean);
}
const baseUrlResolved = path.resolve(paths.appPath, baseUrl);
// We don't need to do anything if `baseUrl` is set to `node_modules`. This is
// the default behavior.
if (path.relative(paths.appNodeModules, baseUrlResolved) === '') {
return null;
}
// Allow the user set the `baseUrl` to `appSrc`.
if (path.relative(paths.appSrc, baseUrlResolved) === '') {
return [paths.appSrc];
}
// If the path is equal to the root directory we ignore it here.
// We don't want to allow importing from the root directly as source files are
// not transpiled outside of `src`. We do allow importing them with the
// absolute path (e.g. `src/Components/Button.js`) but we set that up with
// an alias.
if (path.relative(paths.appPath, baseUrlResolved) === '') {
return null;
}
// Otherwise, throw an error.
throw new Error(
chalk.red.bold(
"Your project's `baseUrl` can only be set to `src` or `node_modules`." +
' Create React App does not support other values at this time.'
)
);
}
/**
* Get webpack aliases based on the baseUrl of a compilerOptions object.
*
* @param {*} options
*/
function getWebpackAliases(options = {}) {
const baseUrl = options.baseUrl;
if (!baseUrl) {
return {};
}
const baseUrlResolved = path.resolve(paths.appPath, baseUrl);
if (path.relative(paths.appPath, baseUrlResolved) === '') {
return {
src: paths.appSrc,
};
}
}
/**
* Get jest aliases based on the baseUrl of a compilerOptions object.
*
* @param {*} options
*/
function getJestAliases(options = {}) {
const baseUrl = options.baseUrl;
if (!baseUrl) {
return {};
}
const baseUrlResolved = path.resolve(paths.appPath, baseUrl);
if (path.relative(paths.appPath, baseUrlResolved) === '') {
return {
'src/(.*)$': '<rootDir>/src/$1',
};
}
}
function getModules() {
// Check if TypeScript is setup
const hasTsConfig = fs.existsSync(paths.appTsConfig);
const hasJsConfig = fs.existsSync(paths.appJsConfig);
if (hasTsConfig && hasJsConfig) {
throw new Error(
'You have both a tsconfig.json and a jsconfig.json. If you are using TypeScript please remove your jsconfig.json file.'
);
}
let config;
// If there's a tsconfig.json we assume it's a
// TypeScript project and set up the config
// based on tsconfig.json
if (hasTsConfig) {
const ts = require(resolve.sync('typescript', {
basedir: paths.appNodeModules,
}));
config = ts.readConfigFile(paths.appTsConfig, ts.sys.readFile).config;
// Otherwise we'll check if there is jsconfig.json
// for non TS projects.
} else if (hasJsConfig) {
config = require(paths.appJsConfig);
}
config = config || {};
const options = config.compilerOptions || {};
const additionalModulePaths = getAdditionalModulePaths(options);
return {
additionalModulePaths: additionalModulePaths,
webpackAliases: getWebpackAliases(options),
jestAliases: getJestAliases(options),
hasTsConfig,
};
}
module.exports = getModules();

90
config/paths.js Normal file
View File

@ -0,0 +1,90 @@
'use strict';
const path = require('path');
const fs = require('fs');
const url = require('url');
// Make sure any symlinks in the project folder are resolved:
// https://github.com/facebook/create-react-app/issues/637
const appDirectory = fs.realpathSync(process.cwd());
const resolveApp = relativePath => path.resolve(appDirectory, relativePath);
const envPublicUrl = process.env.PUBLIC_URL;
function ensureSlash(inputPath, needsSlash) {
const hasSlash = inputPath.endsWith('/');
if (hasSlash && !needsSlash) {
return inputPath.substr(0, inputPath.length - 1);
} else if (!hasSlash && needsSlash) {
return `${inputPath}/`;
} else {
return inputPath;
}
}
const getPublicUrl = appPackageJson =>
envPublicUrl || require(appPackageJson).homepage;
// We use `PUBLIC_URL` environment variable or "homepage" field to infer
// "public path" at which the app is served.
// Webpack needs to know it to put the right <script> hrefs into HTML even in
// single-page apps that may serve index.html for nested URLs like /todos/42.
// We can't use a relative path in HTML because we don't want to load something
// like /todos/42/static/js/bundle.7289d.js. We have to know the root.
function getServedPath(appPackageJson) {
const publicUrl = getPublicUrl(appPackageJson);
const servedUrl =
envPublicUrl || (publicUrl ? url.parse(publicUrl).pathname : '/');
return ensureSlash(servedUrl, true);
}
const moduleFileExtensions = [
'web.mjs',
'mjs',
'web.js',
'js',
'web.ts',
'ts',
'web.tsx',
'tsx',
'json',
'web.jsx',
'jsx',
];
// Resolve file paths in the same order as webpack
const resolveModule = (resolveFn, filePath) => {
const extension = moduleFileExtensions.find(extension =>
fs.existsSync(resolveFn(`${filePath}.${extension}`))
);
if (extension) {
return resolveFn(`${filePath}.${extension}`);
}
return resolveFn(`${filePath}.js`);
};
// config after eject: we're in ./config/
module.exports = {
dotenv: resolveApp('.env'),
appPath: resolveApp('.'),
appBuild: resolveApp('build/react-views'),
appPublic: resolveApp('public'),
appHtml: resolveApp('public/index.html'),
appIndexJs: resolveModule(resolveApp, 'view-src/index'),
appPackageJson: resolveApp('package.json'),
appSrc: resolveApp('view-src'),
appTsConfig: resolveApp('view-src/tsconfig.json'),
appJsConfig: resolveApp('view-src/jsconfig.json'),
yarnLockFile: resolveApp('yarn.lock'),
testsSetup: resolveModule(resolveApp, 'view-src/setupTests'),
proxySetup: resolveApp('view-src/setupProxy.js'),
appNodeModules: resolveApp('node_modules'),
publicUrl: getPublicUrl(resolveApp('package.json')),
servedPath: getServedPath(resolveApp('package.json')),
};
module.exports.moduleFileExtensions = moduleFileExtensions;

35
config/pnpTs.js Normal file
View File

@ -0,0 +1,35 @@
'use strict';
const { resolveModuleName } = require('ts-pnp');
exports.resolveModuleName = (
typescript,
moduleName,
containingFile,
compilerOptions,
resolutionHost
) => {
return resolveModuleName(
moduleName,
containingFile,
compilerOptions,
resolutionHost,
typescript.resolveModuleName
);
};
exports.resolveTypeReferenceDirective = (
typescript,
moduleName,
containingFile,
compilerOptions,
resolutionHost
) => {
return resolveModuleName(
moduleName,
containingFile,
compilerOptions,
resolutionHost,
typescript.resolveTypeReferenceDirective
);
};

683
config/webpack.config.js Normal file
View File

@ -0,0 +1,683 @@
'use strict';
const fs = require('fs');
const isWsl = require('is-wsl');
const path = require('path');
const webpack = require('webpack');
const resolve = require('resolve');
const PnpWebpackPlugin = require('pnp-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
const InlineChunkHtmlPlugin = require('react-dev-utils/InlineChunkHtmlPlugin');
const TerserPlugin = require('terser-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const safePostCssParser = require('postcss-safe-parser');
const ManifestPlugin = require('webpack-manifest-plugin');
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
const WorkboxWebpackPlugin = require('workbox-webpack-plugin');
const WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin');
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
const getCSSModuleLocalIdent = require('react-dev-utils/getCSSModuleLocalIdent');
const paths = require('./paths');
const modules = require('./modules');
const getClientEnvironment = require('./env');
const ModuleNotFoundPlugin = require('react-dev-utils/ModuleNotFoundPlugin');
const ForkTsCheckerWebpackPlugin = require('react-dev-utils/ForkTsCheckerWebpackPlugin');
const typescriptFormatter = require('react-dev-utils/typescriptFormatter');
const eslint = require('eslint');
const postcssNormalize = require('postcss-normalize');
const appPackageJson = require(paths.appPackageJson);
// Source maps are resource heavy and can cause out of memory issue for large source files.
const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== 'false';
// Some apps do not need the benefits of saving a web request, so not inlining the chunk
// makes for a smoother build process.
const shouldInlineRuntimeChunk = process.env.INLINE_RUNTIME_CHUNK !== 'false';
const imageInlineSizeLimit = parseInt(
process.env.IMAGE_INLINE_SIZE_LIMIT || '10000'
);
// Check if TypeScript is setup
const useTypeScript = fs.existsSync(paths.appTsConfig);
// style files regexes
const cssRegex = /\.css$/;
const cssModuleRegex = /\.module\.css$/;
const sassRegex = /\.(scss|sass)$/;
const sassModuleRegex = /\.module\.(scss|sass)$/;
// This is the production and development configuration.
// It is focused on developer experience, fast rebuilds, and a minimal bundle.
module.exports = function(webpackEnv) {
const isEnvDevelopment = webpackEnv === 'development';
const isEnvProduction = webpackEnv === 'production';
// Variable used for enabling profiling in Production
// passed into alias object. Uses a flag if passed into the build command
const isEnvProductionProfile =
isEnvProduction && process.argv.includes('--profile');
// Webpack uses `publicPath` to determine where the app is being served from.
// It requires a trailing slash, or the file assets will get an incorrect path.
// In development, we always serve from the root. This makes config easier.
const publicPath = isEnvProduction
? paths.servedPath
: isEnvDevelopment && '/';
// Some apps do not use client-side routing with pushState.
// For these, "homepage" can be set to "." to enable relative asset paths.
const shouldUseRelativeAssetPaths = publicPath === './';
// `publicUrl` is just like `publicPath`, but we will provide it to our app
// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
// Omit trailing slash as %PUBLIC_URL%/xyz looks better than %PUBLIC_URL%xyz.
const publicUrl = isEnvProduction
? publicPath.slice(0, -1)
: isEnvDevelopment && '';
// Get environment variables to inject into our app.
const env = getClientEnvironment(publicUrl);
// common function to get style loaders
const getStyleLoaders = (cssOptions, preProcessor) => {
const loaders = [
isEnvDevelopment && require.resolve('style-loader'),
isEnvProduction && {
loader: MiniCssExtractPlugin.loader,
options: shouldUseRelativeAssetPaths ? { publicPath: '../../' } : {},
},
{
loader: require.resolve('css-loader'),
options: cssOptions,
},
{
// Options for PostCSS as we reference these options twice
// Adds vendor prefixing based on your specified browser support in
// package.json
loader: require.resolve('postcss-loader'),
options: {
// Necessary for external CSS imports to work
// https://github.com/facebook/create-react-app/issues/2677
ident: 'postcss',
plugins: () => [
require('postcss-flexbugs-fixes'),
require('postcss-preset-env')({
autoprefixer: {
flexbox: 'no-2009',
},
stage: 3,
}),
// Adds PostCSS Normalize as the reset css with default options,
// so that it honors browserslist config in package.json
// which in turn let's users customize the target behavior as per their needs.
postcssNormalize(),
],
sourceMap: isEnvProduction && shouldUseSourceMap,
},
},
].filter(Boolean);
if (preProcessor) {
loaders.push(
{
loader: require.resolve('resolve-url-loader'),
options: {
sourceMap: isEnvProduction && shouldUseSourceMap,
},
},
{
loader: require.resolve(preProcessor),
options: {
sourceMap: true,
},
}
);
}
return loaders;
};
return {
mode: isEnvProduction ? 'production' : isEnvDevelopment && 'development',
// Stop compilation early in production
bail: isEnvProduction,
devtool: isEnvProduction
? shouldUseSourceMap
? 'source-map'
: false
: isEnvDevelopment && 'cheap-module-source-map',
// These are the "entry points" to our application.
// This means they will be the "root" imports that are included in JS bundle.
entry: [
// Include an alternative client for WebpackDevServer. A client's job is to
// connect to WebpackDevServer by a socket and get notified about changes.
// When you save a file, the client will either apply hot updates (in case
// of CSS changes), or refresh the page (in case of JS changes). When you
// make a syntax error, this client will display a syntax error overlay.
// Note: instead of the default WebpackDevServer client, we use a custom one
// to bring better experience for Create React App users. You can replace
// the line below with these two lines if you prefer the stock client:
// require.resolve('webpack-dev-server/client') + '?/',
// require.resolve('webpack/hot/dev-server'),
isEnvDevelopment &&
require.resolve('react-dev-utils/webpackHotDevClient'),
// Finally, this is your app's code:
paths.appIndexJs,
// We include the app code last so that if there is a runtime error during
// initialization, it doesn't blow up the WebpackDevServer client, and
// changing JS code would still trigger a refresh.
].filter(Boolean),
output: {
// The build folder.
path: isEnvProduction ? paths.appBuild : undefined,
// Add /* filename */ comments to generated require()s in the output.
pathinfo: isEnvDevelopment,
// There will be one main bundle, and one file per asynchronous chunk.
// In development, it does not produce real files.
filename: isEnvProduction
? 'static/js/[name].[contenthash:8].js'
: isEnvDevelopment && 'static/js/bundle.js',
// TODO: remove this when upgrading to webpack 5
futureEmitAssets: true,
// There are also additional JS chunk files if you use code splitting.
chunkFilename: isEnvProduction
? 'static/js/[name].[contenthash:8].chunk.js'
: isEnvDevelopment && 'static/js/[name].chunk.js',
// We inferred the "public path" (such as / or /my-project) from homepage.
// We use "/" in development.
publicPath: publicPath,
// Point sourcemap entries to original disk location (format as URL on Windows)
devtoolModuleFilenameTemplate: isEnvProduction
? info =>
path
.relative(paths.appSrc, info.absoluteResourcePath)
.replace(/\\/g, '/')
: isEnvDevelopment &&
(info => path.resolve(info.absoluteResourcePath).replace(/\\/g, '/')),
// Prevents conflicts when multiple Webpack runtimes (from different apps)
// are used on the same page.
jsonpFunction: `webpackJsonp${appPackageJson.name}`,
// this defaults to 'window', but by setting it to 'this' then
// module chunks which are built will work in web workers as well.
globalObject: 'this',
},
optimization: {
minimize: isEnvProduction,
minimizer: [
// This is only used in production mode
new TerserPlugin({
terserOptions: {
parse: {
// We want terser to parse ecma 8 code. However, we don't want it
// to apply any minification steps that turns valid ecma 5 code
// into invalid ecma 5 code. This is why the 'compress' and 'output'
// sections only apply transformations that are ecma 5 safe
// https://github.com/facebook/create-react-app/pull/4234
ecma: 8,
},
compress: {
ecma: 5,
warnings: false,
// Disabled because of an issue with Uglify breaking seemingly valid code:
// https://github.com/facebook/create-react-app/issues/2376
// Pending further investigation:
// https://github.com/mishoo/UglifyJS2/issues/2011
comparisons: false,
// Disabled because of an issue with Terser breaking valid code:
// https://github.com/facebook/create-react-app/issues/5250
// Pending further investigation:
// https://github.com/terser-js/terser/issues/120
inline: 2,
},
mangle: {
safari10: true,
},
// Added for profiling in devtools
keep_classnames: isEnvProductionProfile,
keep_fnames: isEnvProductionProfile,
output: {
ecma: 5,
comments: false,
// Turned on because emoji and regex is not minified properly using default
// https://github.com/facebook/create-react-app/issues/2488
ascii_only: true,
},
},
// Use multi-process parallel running to improve the build speed
// Default number of concurrent runs: os.cpus().length - 1
// Disabled on WSL (Windows Subsystem for Linux) due to an issue with Terser
// https://github.com/webpack-contrib/terser-webpack-plugin/issues/21
parallel: !isWsl,
// Enable file caching
cache: true,
sourceMap: shouldUseSourceMap,
}),
// This is only used in production mode
new OptimizeCSSAssetsPlugin({
cssProcessorOptions: {
parser: safePostCssParser,
map: shouldUseSourceMap
? {
// `inline: false` forces the sourcemap to be output into a
// separate file
inline: false,
// `annotation: true` appends the sourceMappingURL to the end of
// the css file, helping the browser find the sourcemap
annotation: true,
}
: false,
},
}),
],
// Automatically split vendor and commons
// https://twitter.com/wSokra/status/969633336732905474
// https://medium.com/webpack/webpack-4-code-splitting-chunk-graph-and-the-splitchunks-optimization-be739a861366
splitChunks: {
chunks: 'all',
name: false,
},
// Keep the runtime chunk separated to enable long term caching
// https://twitter.com/wSokra/status/969679223278505985
// https://github.com/facebook/create-react-app/issues/5358
runtimeChunk: {
name: entrypoint => `runtime-${entrypoint.name}`,
},
},
resolve: {
// This allows you to set a fallback for where Webpack should look for modules.
// We placed these paths second because we want `node_modules` to "win"
// if there are any conflicts. This matches Node resolution mechanism.
// https://github.com/facebook/create-react-app/issues/253
modules: ['node_modules', paths.appNodeModules].concat(
modules.additionalModulePaths || []
),
// These are the reasonable defaults supported by the Node ecosystem.
// We also include JSX as a common component filename extension to support
// some tools, although we do not recommend using it, see:
// https://github.com/facebook/create-react-app/issues/290
// `web` extension prefixes have been added for better support
// for React Native Web.
extensions: paths.moduleFileExtensions
.map(ext => `.${ext}`)
.filter(ext => useTypeScript || !ext.includes('ts')),
alias: {
// Support React Native Web
// https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
'react-native': 'react-native-web',
// Allows for better profiling with ReactDevTools
...(isEnvProductionProfile && {
'react-dom$': 'react-dom/profiling',
'scheduler/tracing': 'scheduler/tracing-profiling',
}),
images: `${paths.appSrc}/images/`,
components: `${paths.appSrc}/components/`,
utils: `${paths.appSrc}/utils`,
...(modules.webpackAliases || {}),
},
plugins: [
// Adds support for installing with Plug'n'Play, leading to faster installs and adding
// guards against forgotten dependencies and such.
PnpWebpackPlugin,
// Prevents users from importing files from outside of src/ (or node_modules/).
// This often causes confusion because we only process files within src/ with babel.
// To fix this, we prevent you from importing files out of src/ -- if you'd like to,
// please link the files into your node_modules/ and let module-resolution kick in.
// Make sure your source files are compiled, as they will not be processed in any way.
new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
],
},
resolveLoader: {
plugins: [
// Also related to Plug'n'Play, but this time it tells Webpack to load its loaders
// from the current package.
PnpWebpackPlugin.moduleLoader(module),
],
},
module: {
strictExportPresence: true,
rules: [
// Disable require.ensure as it's not a standard language feature.
{ parser: { requireEnsure: false } },
// First, run the linter.
// It's important to do this before Babel processes the JS.
{
test: /\.(js|mjs|jsx|ts|tsx)$/,
enforce: 'pre',
use: [
{
options: {
cache: true,
formatter: require.resolve('react-dev-utils/eslintFormatter'),
eslintPath: require.resolve('eslint'),
resolvePluginsRelativeTo: __dirname,
},
loader: require.resolve('eslint-loader'),
},
],
include: paths.appSrc,
},
{
// "oneOf" will traverse all following loaders until one will
// match the requirements. When no loader matches it will fall
// back to the "file" loader at the end of the loader list.
oneOf: [
// "url" loader works like "file" loader except that it embeds assets
// smaller than specified limit in bytes as data URLs to avoid requests.
// A missing `test` is equivalent to a match.
{
test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
loader: require.resolve('url-loader'),
options: {
limit: imageInlineSizeLimit,
name: 'static/media/[name].[hash:8].[ext]',
},
},
// Process application JS with Babel.
// The preset includes JSX, Flow, TypeScript, and some ESnext features.
{
test: /\.(js|mjs|jsx|ts|tsx)$/,
include: paths.appSrc,
loader: require.resolve('babel-loader'),
options: {
customize: require.resolve(
'babel-preset-react-app/webpack-overrides'
),
plugins: [
[
require.resolve('babel-plugin-named-asset-import'),
{
loaderMap: {
svg: {
ReactComponent:
'@svgr/webpack?-svgo,+titleProp,+ref![path]',
},
},
},
],
],
// This is a feature of `babel-loader` for webpack (not Babel itself).
// It enables caching results in ./node_modules/.cache/babel-loader/
// directory for faster rebuilds.
cacheDirectory: true,
// See #6846 for context on why cacheCompression is disabled
cacheCompression: false,
compact: isEnvProduction,
},
},
// Process any JS outside of the app with Babel.
// Unlike the application JS, we only compile the standard ES features.
{
test: /\.(js|mjs)$/,
exclude: /@babel(?:\/|\\{1,2})runtime/,
loader: require.resolve('babel-loader'),
options: {
babelrc: false,
configFile: false,
compact: false,
presets: [
[
require.resolve('babel-preset-react-app/dependencies'),
{ helpers: true },
],
],
cacheDirectory: true,
// See #6846 for context on why cacheCompression is disabled
cacheCompression: false,
// If an error happens in a package, it's possible to be
// because it was compiled. Thus, we don't want the browser
// debugger to show the original code. Instead, the code
// being evaluated would be much more helpful.
sourceMaps: false,
},
},
// "postcss" loader applies autoprefixer to our CSS.
// "css" loader resolves paths in CSS and adds assets as dependencies.
// "style" loader turns CSS into JS modules that inject <style> tags.
// In production, we use MiniCSSExtractPlugin to extract that CSS
// to a file, but in development "style" loader enables hot editing
// of CSS.
// By default we support CSS Modules with the extension .module.css
{
test: cssRegex,
exclude: cssModuleRegex,
use: getStyleLoaders({
importLoaders: 1,
sourceMap: isEnvProduction && shouldUseSourceMap,
}),
// Don't consider CSS imports dead code even if the
// containing package claims to have no side effects.
// Remove this when webpack adds a warning or an error for this.
// See https://github.com/webpack/webpack/issues/6571
sideEffects: true,
},
// Adds support for CSS Modules (https://github.com/css-modules/css-modules)
// using the extension .module.css
{
test: cssModuleRegex,
use: getStyleLoaders({
importLoaders: 1,
sourceMap: isEnvProduction && shouldUseSourceMap,
modules: true,
getLocalIdent: getCSSModuleLocalIdent,
}),
},
// Opt-in support for SASS (using .scss or .sass extensions).
// By default we support SASS Modules with the
// extensions .module.scss or .module.sass
{
test: sassRegex,
exclude: sassModuleRegex,
use: getStyleLoaders(
{
importLoaders: 2,
sourceMap: isEnvProduction && shouldUseSourceMap,
},
'sass-loader'
),
// Don't consider CSS imports dead code even if the
// containing package claims to have no side effects.
// Remove this when webpack adds a warning or an error for this.
// See https://github.com/webpack/webpack/issues/6571
sideEffects: true,
},
// Adds support for CSS Modules, but using SASS
// using the extension .module.scss or .module.sass
{
test: sassModuleRegex,
use: getStyleLoaders(
{
importLoaders: 2,
sourceMap: isEnvProduction && shouldUseSourceMap,
modules: true,
getLocalIdent: getCSSModuleLocalIdent,
},
'sass-loader'
),
},
// "file" loader makes sure those assets get served by WebpackDevServer.
// When you `import` an asset, you get its (virtual) filename.
// In production, they would get copied to the `build` folder.
// This loader doesn't use a "test" so it will catch all modules
// that fall through the other loaders.
{
loader: require.resolve('file-loader'),
// Exclude `js` files to keep "css" loader working as it injects
// its runtime that would otherwise be processed through "file" loader.
// Also exclude `html` and `json` extensions so they get processed
// by webpacks internal loaders.
exclude: [/\.(js|mjs|jsx|ts|tsx)$/, /\.html$/, /\.json$/],
options: {
name: 'static/media/[name].[hash:8].[ext]',
},
},
// ** STOP ** Are you adding a new loader?
// Make sure to add the new loader(s) before the "file" loader.
],
},
],
},
plugins: [
// Generates an `index.html` file with the <script> injected.
new HtmlWebpackPlugin(
Object.assign(
{},
{
inject: true,
template: paths.appHtml,
},
isEnvProduction
? {
minify: {
removeComments: true,
collapseWhitespace: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true,
},
}
: undefined
)
),
// Inlines the webpack runtime script. This script is too small to warrant
// a network request.
// https://github.com/facebook/create-react-app/issues/5358
isEnvProduction &&
shouldInlineRuntimeChunk &&
new InlineChunkHtmlPlugin(HtmlWebpackPlugin, [/runtime-.+[.]js/]),
// Makes some environment variables available in index.html.
// The public URL is available as %PUBLIC_URL% in index.html, e.g.:
// <link rel="icon" href="%PUBLIC_URL%/favicon.ico">
// In production, it will be an empty string unless you specify "homepage"
// in `package.json`, in which case it will be the pathname of that URL.
// In development, this will be an empty string.
new InterpolateHtmlPlugin(HtmlWebpackPlugin, env.raw),
// This gives some necessary context to module not found errors, such as
// the requesting resource.
new ModuleNotFoundPlugin(paths.appPath),
// Makes some environment variables available to the JS code, for example:
// if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`.
// It is absolutely essential that NODE_ENV is set to production
// during a production build.
// Otherwise React will be compiled in the very slow development mode.
new webpack.DefinePlugin(env.stringified),
// This is necessary to emit hot updates (currently CSS only):
isEnvDevelopment && new webpack.HotModuleReplacementPlugin(),
// Watcher doesn't work well if you mistype casing in a path so we use
// a plugin that prints an error when you attempt to do this.
// See https://github.com/facebook/create-react-app/issues/240
isEnvDevelopment && new CaseSensitivePathsPlugin(),
// If you require a missing module and then `npm install` it, you still have
// to restart the development server for Webpack to discover it. This plugin
// makes the discovery automatic so you don't have to restart.
// See https://github.com/facebook/create-react-app/issues/186
isEnvDevelopment &&
new WatchMissingNodeModulesPlugin(paths.appNodeModules),
isEnvProduction &&
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: 'static/css/[name].[contenthash:8].css',
chunkFilename: 'static/css/[name].[contenthash:8].chunk.css',
}),
// Generate an asset manifest file with the following content:
// - "files" key: Mapping of all asset filenames to their corresponding
// output file so that tools can pick it up without having to parse
// `index.html`
// - "entrypoints" key: Array of files which are included in `index.html`,
// can be used to reconstruct the HTML if necessary
new ManifestPlugin({
fileName: 'asset-manifest.json',
publicPath: publicPath,
generate: (seed, files, entrypoints) => {
const manifestFiles = files.reduce((manifest, file) => {
manifest[file.name] = file.path;
return manifest;
}, seed);
const entrypointFiles = entrypoints.main.filter(
fileName => !fileName.endsWith('.map')
);
return {
files: manifestFiles,
entrypoints: entrypointFiles,
};
},
}),
// Moment.js is an extremely popular library that bundles large locale files
// by default due to how Webpack interprets its code. This is a practical
// solution that requires the user to opt into importing specific locales.
// https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
// You can remove this if you don't use Moment.js:
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
// Generate a service worker script that will precache, and keep up to date,
// the HTML & assets that are part of the Webpack build.
isEnvProduction &&
new WorkboxWebpackPlugin.GenerateSW({
clientsClaim: true,
exclude: [/\.map$/, /asset-manifest\.json$/],
importWorkboxFrom: 'cdn',
navigateFallback: publicUrl + '/index.html',
navigateFallbackBlacklist: [
// Exclude URLs starting with /_, as they're likely an API call
new RegExp('^/_'),
// Exclude any URLs whose last part seems to be a file extension
// as they're likely a resource and not a SPA route.
// URLs containing a "?" character won't be blacklisted as they're likely
// a route with query params (e.g. auth callbacks).
new RegExp('/[^/?]+\\.[^/]+$'),
],
}),
// TypeScript type checking
useTypeScript &&
new ForkTsCheckerWebpackPlugin({
typescript: resolve.sync('typescript', {
basedir: paths.appNodeModules,
}),
async: isEnvDevelopment,
useTypescriptIncrementalApi: true,
checkSyntacticErrors: true,
resolveModuleNameModule: process.versions.pnp
? `${__dirname}/pnpTs.js`
: undefined,
resolveTypeReferenceDirectiveModule: process.versions.pnp
? `${__dirname}/pnpTs.js`
: undefined,
tsconfig: paths.appTsConfig,
reportFiles: [
'**',
'!**/__tests__/**',
'!**/?(*.)(spec|test).*',
'!**/src/setupProxy.*',
'!**/src/setupTests.*',
],
silent: true,
// The formatter is invoked directly in WebpackDevServerUtils during development
formatter: isEnvProduction ? typescriptFormatter : undefined,
}),
].filter(Boolean),
// Some libraries import Node modules but don't use them in the browser.
// Tell Webpack to provide empty mocks for them so importing them works.
node: {
module: 'empty',
dgram: 'empty',
dns: 'mock',
fs: 'empty',
http2: 'empty',
net: 'empty',
tls: 'empty',
child_process: 'empty',
},
// Turn off performance processing because we utilize
// our own hints via the FileSizeReporter
performance: false,
};
};

View File

@ -0,0 +1,104 @@
'use strict';
const errorOverlayMiddleware = require('react-dev-utils/errorOverlayMiddleware');
const evalSourceMapMiddleware = require('react-dev-utils/evalSourceMapMiddleware');
const noopServiceWorkerMiddleware = require('react-dev-utils/noopServiceWorkerMiddleware');
const ignoredFiles = require('react-dev-utils/ignoredFiles');
const paths = require('./paths');
const fs = require('fs');
const protocol = process.env.HTTPS === 'true' ? 'https' : 'http';
const host = process.env.HOST || '0.0.0.0';
module.exports = function(proxy, allowedHost) {
return {
// WebpackDevServer 2.4.3 introduced a security fix that prevents remote
// websites from potentially accessing local content through DNS rebinding:
// https://github.com/webpack/webpack-dev-server/issues/887
// https://medium.com/webpack/webpack-dev-server-middleware-security-issues-1489d950874a
// However, it made several existing use cases such as development in cloud
// environment or subdomains in development significantly more complicated:
// https://github.com/facebook/create-react-app/issues/2271
// https://github.com/facebook/create-react-app/issues/2233
// While we're investigating better solutions, for now we will take a
// compromise. Since our WDS configuration only serves files in the `public`
// folder we won't consider accessing them a vulnerability. However, if you
// use the `proxy` feature, it gets more dangerous because it can expose
// remote code execution vulnerabilities in backends like Django and Rails.
// So we will disable the host check normally, but enable it if you have
// specified the `proxy` setting. Finally, we let you override it if you
// really know what you're doing with a special environment variable.
disableHostCheck:
!proxy || process.env.DANGEROUSLY_DISABLE_HOST_CHECK === 'true',
// Enable gzip compression of generated files.
compress: true,
// Silence WebpackDevServer's own logs since they're generally not useful.
// It will still show compile warnings and errors with this setting.
clientLogLevel: 'none',
// By default WebpackDevServer serves physical files from current directory
// in addition to all the virtual build products that it serves from memory.
// This is confusing because those files wont automatically be available in
// production build folder unless we copy them. However, copying the whole
// project directory is dangerous because we may expose sensitive files.
// Instead, we establish a convention that only files in `public` directory
// get served. Our build script will copy `public` into the `build` folder.
// In `index.html`, you can get URL of `public` folder with %PUBLIC_URL%:
// <link rel="icon" href="%PUBLIC_URL%/favicon.ico">
// In JavaScript code, you can access it with `process.env.PUBLIC_URL`.
// Note that we only recommend to use `public` folder as an escape hatch
// for files like `favicon.ico`, `manifest.json`, and libraries that are
// for some reason broken when imported through Webpack. If you just want to
// use an image, put it in `src` and `import` it from JavaScript instead.
contentBase: paths.appPublic,
// By default files from `contentBase` will not trigger a page reload.
watchContentBase: true,
// Enable hot reloading server. It will provide /sockjs-node/ endpoint
// for the WebpackDevServer client so it can learn when the files were
// updated. The WebpackDevServer client is included as an entry point
// in the Webpack development configuration. Note that only changes
// to CSS are currently hot reloaded. JS changes will refresh the browser.
hot: true,
// It is important to tell WebpackDevServer to use the same "root" path
// as we specified in the config. In development, we always serve from /.
publicPath: '/',
// WebpackDevServer is noisy by default so we emit custom message instead
// by listening to the compiler events with `compiler.hooks[...].tap` calls above.
quiet: true,
// Reportedly, this avoids CPU overload on some systems.
// https://github.com/facebook/create-react-app/issues/293
// src/node_modules is not ignored to support absolute imports
// https://github.com/facebook/create-react-app/issues/1065
watchOptions: {
ignored: ignoredFiles(paths.appSrc),
},
// Enable HTTPS if the HTTPS environment variable is set to 'true'
https: protocol === 'https',
host,
overlay: false,
historyApiFallback: {
// Paths with dots should still use the history fallback.
// See https://github.com/facebook/create-react-app/issues/387.
disableDotRule: true,
},
public: allowedHost,
proxy,
before(app, server) {
if (fs.existsSync(paths.proxySetup)) {
// This registers user provided middleware for proxy reasons
require(paths.proxySetup)(app);
}
// This lets us fetch source contents from webpack for the error overlay
app.use(evalSourceMapMiddleware(server));
// This lets us open files from the runtime error overlay.
app.use(errorOverlayMiddleware());
// This service worker file is effectively a 'no-op' that will reset any
// previous service worker registered for the same host:port combination.
// We do this in development to avoid hitting the production cache if
// it used the same host and port.
// https://github.com/facebook/create-react-app/issues/2272#issuecomment-302832432
app.use(noopServiceWorkerMiddleware());
},
};
};

20043
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

522
package.json Normal file
View File

@ -0,0 +1,522 @@
{
"name": "k210-extension",
"displayName": "Kendryte Dev Tools",
"description": "A develop tool for kendryte chip.",
"publisher": "Kendryte",
"repository": "https://git.b-bug.org/linzhanjie_intern/k210-extension",
"version": "0.0.1",
"engines": {
"vscode": "^1.40.0"
},
"categories": [
"Other"
],
"activationEvents": [
"*"
],
"main": "./build/extension.js",
"contributes": {
"jsonValidation": [
{
"fileMatch": "kendryte-package.json",
"url": "./resources/schema.json"
}
],
"extensionPack": ["ms-vscode.cpptools"],
"configuration": [
{
"title": "k210-openocd",
"properties": {
"openocd.useKey": {
"type": "string",
"enum": [
"JTag",
"FTDI"
],
"default": "JTag",
"description": "Select how openocd is configured.",
"enumDescriptions": [
"Use JTag interface",
"Use FTDI interface"
]
},
"openocd.port": {
"type": "number",
"default": 0,
"minimum": 0,
"maximum": 65535,
"description": "Openocd listen port, 0 means auto select"
}
}
},
{
"title": "k210-JLink",
"properties": {
"JTag.ID": {
"type": "number",
"default": 0,
"description": "Serial number of JLink device, 0 means use first available"
},
"JTag.speed": {
"type": "number",
"default": 30000,
"description": "khz"
}
}
},
{
"title": "k210-FTDI",
"properties": {
"FTDI.speed": {
"type": "number",
"default": 25000,
"description": "khz"
},
"FTDI.vid_pid": {
"type": "string",
"default": "0403 6014",
"description": "FTDI USB device VID PID value (two HEX string, eg: \"1b2b 3c4d\")"
},
"FTDI.layout": {
"type": "string",
"default": "00e8 00eb",
"description": "Layout init value (two HEX string, eg: \"1b2b 3c4d\")"
},
"FTDI.tdo-fe": {
"type": "boolean",
"default": true,
"description": "ftdi_tdo_sample_edge_value"
}
}
}
],
"commands": [
{
"command": "extension.reinstallPackages",
"title": "Reinstall Packages",
"category": "K210-Dev-Extension"
},
{
"command": "extension.build",
"title": "Build",
"category": "K210-Dev-Extension"
},
{
"command": "extension.createHelloworld",
"title": "Create Helloworld Project",
"category": "K210-Dev-Extension"
},
{
"command": "extension.buildAndUpload",
"title": "Build and upload",
"category": "K210-Dev-Extension"
},
{
"command": "extension.debug",
"title": "Debug",
"category": "K210-Dev-Extension"
},
{
"command": "extension.configGenerate",
"title": "Config generate",
"category": "K210-Dev-Extension"
},
{
"command": "extension.openocd.start",
"title": "Start Openocd",
"category": "Openocd"
},
{
"command": "extension.openocd.stop",
"title": "Stop Openocd",
"category": "Openocd"
},
{
"command": "extension.openocd.restart",
"title": "Restart Openocd",
"category": "Openocd"
},
{
"command": "extension.cmakelistGenerate",
"title": "Generate CMakeLists",
"category": "K210-Dev-Extension"
},
{
"command": "extension.pickDevice",
"title": "Pick Device",
"category": "K210-Dev-Extension"
},
{
"command": "packageDependencies.refresh",
"title": "Refresh dependencies",
"icon": {
"dark": "resources/dark/refresh.svg",
"light": "resources/light/refresh.svg"
}
},
{
"command": "packageDependencies.download",
"title": "Download Packages",
"icon": {
"dark": "resources/dark/download.svg",
"light": "resources/light/download.svg"
}
},
{
"command": "packageDependencies.createWebview",
"title": "Download Packages",
"icon": {
"dark": "resources/dark/explore.svg",
"light": "resources/light/explore.svg"
}
},
{
"command": "packageDependencies.delete",
"title": "Download Packages",
"icon": {
"dark": "resources/dark/delete.svg",
"light": "resources/light/delete.svg"
}
},
{
"command": "extension.addDependency",
"title": "Add Package",
"category": "K210-Dev-Extension"
},
{
"command": "extension.openSerialPort",
"title": "Open serial port output channel",
"category": "K210-Dev-Extension"
}
],
"viewsContainers": {
"activitybar": [
{
"id": "package-explorer",
"title": "Package Explorer",
"icon": "resources/dark/core.svg"
}
]
},
"views": {
"package-explorer": [
{
"id": "packageDependencies",
"name": "Dependencies"
}
]
},
"menus": {
"view/title": [
{
"command": "packageDependencies.createWebview",
"when": "view == packageDependencies",
"group": "navigation@3"
},
{
"command": "packageDependencies.download",
"when": "view == packageDependencies",
"group": "navigation@2"
},
{
"command": "packageDependencies.refresh",
"when": "view == packageDependencies",
"group": "navigation@1"
}
],
"view/item/context": [
{
"command": "packageDependencies.delete",
"when": "view == packageDependencies",
"group": "inline"
}
]
},
"breakpoints": [
{
"language": "c"
},
{
"language": "cpp"
},
{
"language": "asm"
}
],
"debuggers": [
{
"type": "kendryte",
"program": "./build/debugadapter.js",
"runtime": "node",
"label": "Kendryte",
"configurationAttributes": {
"launch": {
"required": [
"target"
],
"properties": {
"id": {
"type": "string",
"description": "ID of this config"
},
"executable": {
"type": "string",
"description": "Path of executable"
},
"target": {
"type": "string",
"description": "openocd server ip port"
},
"gdbpath": {
"type": "string",
"description": "gdb working directory"
},
"cwd": {
"type": "string",
"description": "gdb working directory"
},
"debuggerArgs": {
"type": "array",
"description": "Additional arguments to pass to GDB",
"default": []
},
"autorun": {
"type": "array",
"description": "GDB commands to run when starting to debug",
"default": []
},
"env": {
"type": "object"
}
}
}
},
"initialConfigurations": [
{
"id": "kendryte",
"name": "Kendryte Debug",
"type": "kendryte",
"cwd": "${workspaceRoot}/build"
}
],
"configurationSnippets": [
{
"label": "Kendryte: Debug Program",
"description": "Debug program with OpenOCD",
"body": {
"type": "kendryte",
"name": "${2:Kendryte Debug}",
"target": "${1:DefaultProjectName}",
"cwd": "^\"\\${workspaceRoot}/build\""
}
}
]
}
]
},
"scripts": {
"postinstall": "./node_modules/.bin/electron-rebuild --version 6.0.0 && node ./node_modules/vscode/bin/install",
"vscode:prepublish": "webpack --mode production && node scripts/build.js",
"compile": "tsc -p src/tsconfig.json",
"test": "node ./build/test/runTest.js",
"dev": "tsc -watch -p src/tsconfig.json",
"build": "node scripts/build.js",
"watch": "node scripts/start.js",
"webpack-dev": "webpack --mode development --watch"
},
"devDependencies": {
"@babel/core": "^7.6.0",
"@types/adm-zip": "^0.4.32",
"@types/chmodr": "^1.0.0",
"@types/glob": "^7.1.1",
"@types/jest": "^24.0.19",
"@types/jszip": "^3.1.6",
"@types/lodash": "^4.14.144",
"@types/mocha": "^5.2.6",
"@types/module-alias": "^2.0.0",
"@types/node": "^10.12.21",
"@types/node-7z": "^0.4.2",
"@types/react": "^16.9.7",
"@types/react-dom": "^16.9.2",
"@types/react-router-dom": "^5.1.0",
"@types/serialport": "^7.0.4",
"@types/split2": "^2.1.6",
"@typescript-eslint/eslint-plugin": "^2.7.0",
"@typescript-eslint/parser": "^2.7.0",
"autoprefixer": "^7.1.6",
"babel-eslint": "^10.0.3",
"babel-jest": "^24.9.0",
"babel-loader": "^8.0.6",
"babel-plugin-named-asset-import": "^0.3.4",
"babel-preset-react-app": "^9.0.2",
"case-sensitive-paths-webpack-plugin": "^2.2.0",
"css-loader": "^2.1.1",
"electron-rebuild": "^1.8.6",
"eslint": "^6.5.1",
"eslint-config-react-app": "^5.0.2",
"eslint-loader": "^3.0.2",
"eslint-plugin-flowtype": "^3.13.0",
"eslint-plugin-import": "^2.18.2",
"eslint-plugin-jsx-a11y": "^6.2.3",
"eslint-plugin-react": "^7.14.3",
"eslint-plugin-react-hooks": "^1.7.0",
"extract-text-webpack-plugin": "^3.0.2",
"fork-ts-checker-webpack-plugin": "^0.2.10",
"glob": "^7.1.4",
"jest": "^24.9.0",
"jest-environment-jsdom-fourteen": "^0.1.0",
"jest-resolve": "^24.9.0",
"jest-watch-typeahead": "^0.4.0",
"mocha": "^6.1.4",
"module-alias": "^2.2.2",
"node-sass": "^4.13.0",
"rewire": "^4.0.1",
"sass-loader": "^7.2.0",
"terser-webpack-plugin": "^1.4.1",
"ts-jest": "^22.0.1",
"ts-loader": "^6.0.0",
"tsconfig-paths-webpack-plugin": "^2.0.0",
"tslint": "^5.20.0",
"tslint-config-prettier": "^1.18.0",
"tslint-react": "^3.6.0",
"typescript": "^3.4.3",
"uglifyjs-webpack-plugin": "^1.2.5",
"vscode": "^1.1.36",
"vscode-test": "^1.0.0-next.0",
"webpack": "^4.41.0",
"webpack-cli": "^3.3.10",
"webpack-dev-server": "^3.2.1",
"webpack-manifest-plugin": "^2.1.1",
"workbox-webpack-plugin": "^4.3.1"
},
"dependencies": {
"7zip-bin": "^5.0.3",
"7zip-bin-wrapper": "^1.0.10",
"@serialport/binding-mock": "^2.0.3",
"@serialport/bindings": "^2.0.2",
"@svgr/webpack": "4.3.2",
"adm-zip": "^0.4.13",
"axios": "^0.19.0",
"camelcase": "^5.2.0",
"chalk": "1.1.3",
"chmodr": "^1.2.0",
"dotenv": "6.2.0",
"dotenv-expand": "5.1.0",
"fast-glob": "^3.1.0",
"file-loader": "3.0.1",
"fs-extra": "7.0.1",
"html-webpack-plugin": "4.0.0-beta.5",
"identity-obj-proxy": "3.0.0",
"is-wsl": "^1.1.0",
"jszip": "^3.2.2",
"lodash": "^4.17.15",
"mini-css-extract-plugin": "0.8.0",
"node-7z": "^1.1.1",
"node-gyp": "^6.0.1",
"object-assign": "4.1.1",
"optimize-css-assets-webpack-plugin": "5.0.3",
"original-fs": "^1.1.0",
"pnp-webpack-plugin": "1.5.0",
"postcss-flexbugs-fixes": "4.1.0",
"postcss-loader": "3.0.0",
"postcss-normalize": "7.0.1",
"postcss-preset-env": "6.7.0",
"postcss-safe-parser": "4.0.1",
"promise": "8.0.1",
"raf": "3.4.0",
"react": "^16.10.2",
"react-app-polyfill": "^1.0.4",
"react-dev-utils": "^9.1.0",
"react-dom": "^16.10.2",
"react-router-dom": "^5.1.2",
"resolve": "1.12.0",
"resolve-url-loader": "3.1.0",
"semver": "6.3.0",
"serialport": "^7.1.5",
"source-map-loader": "^0.2.1",
"style-loader": "1.0.0",
"sudo-prompt": "^9.1.1",
"sw-precache-webpack-plugin": "0.11.4",
"ts-pnp": "1.1.4",
"url-loader": "2.1.0",
"vscode-debugadapter": "^1.35.0",
"vscode-debugprotocol": "^1.35.0",
"vscode-nls": "^4.1.1",
"whatwg-fetch": "2.0.3"
},
"_moduleAliases": {
"@command/*": "./src/command",
"@utils/*": "./src/utils",
"@debug/*": "./src/debug",
"@service/*": "./src/service",
"@common/*": "./src/common"
},
"babel": {
"presets": [
"react-app"
]
},
"jest": {
"roots": [
"<rootDir>/src"
],
"collectCoverageFrom": [
"src/**/*.{js,jsx,ts,tsx}",
"!src/**/*.d.ts"
],
"setupFiles": [
"react-app-polyfill/jsdom"
],
"setupFilesAfterEnv": [],
"testMatch": [
"<rootDir>/src/**/__tests__/**/*.{js,jsx,ts,tsx}",
"<rootDir>/src/**/*.{spec,test}.{js,jsx,ts,tsx}"
],
"testEnvironment": "jest-environment-jsdom-fourteen",
"transform": {
"^.+\\.(js|jsx|ts|tsx)$": "<rootDir>/node_modules/babel-jest",
"^.+\\.css$": "<rootDir>/config/jest/cssTransform.js",
"^(?!.*\\.(js|jsx|ts|tsx|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
},
"transformIgnorePatterns": [
"[/\\\\]node_modules[/\\\\].+\\.(js|jsx|ts|tsx)$",
"^.+\\.module\\.(css|sass|scss)$"
],
"modulePaths": [],
"moduleNameMapper": {
"^react-native$": "react-native-web",
"^.+\\.module\\.(css|sass|scss)$": "identity-obj-proxy"
},
"moduleFileExtensions": [
"web.js",
"js",
"web.ts",
"ts",
"web.tsx",
"tsx",
"json",
"web.jsx",
"jsx",
"node"
],
"watchPlugins": [
"jest-watch-typeahead/filename",
"jest-watch-typeahead/testname"
]
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}

BIN
public/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

40
public/index.html Normal file
View File

@ -0,0 +1,40 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="theme-color" content="#000000">
<!--
manifest.json provides metadata used when your web app is added to the
homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json">
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>

11
public/kendryte.svg Normal file
View File

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 23.0.3, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg version="1.1" id="图层_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 24 24" style="enable-background:new 0 0 24 24;" xml:space="preserve">
<style type="text/css">
.st0{fill:#249EDC;}
</style>
<path class="st0" d="M5.7,5v14h3V5H5.7z"/>
<path class="st0" d="M12.9,5L8.7,9.5l0,4.4L17,5H12.9z"/>
<path class="st0" d="M9,13.5l4.8,5.5h4L11,11.3L9,13.5z"/>
</svg>

After

Width:  |  Height:  |  Size: 565 B

15
public/manifest.json Normal file
View File

@ -0,0 +1,15 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
}
],
"start_url": "./index.html",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}

14
resources/dark/core.svg Normal file
View File

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 23.0.3, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg version="1.1" id="图层_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 201.4 200" style="enable-background:new 0 0 201.4 200;" xml:space="preserve">
<style type="text/css">
.st0{fill:#989898;}
</style>
<g>
<path class="st0" d="M136.5,64.1H64.1v72.4h72.4V64.1z M125.7,125.3h-50v-50h50V125.3z"/>
<path class="st0" d="M200.8,106V94.7h-24.6V67h24.4V55.7H176V24.5h-31.1V0.6h-11.3v23.9h-27.7V0.6H94.6v23.9H66.9V0.6H55.6v23.9
H24.5v31.1H0V67h24.6v27.7H0V106h24.6v27.7H0V145h24.6v31.1h31.1V200H67v-23.9h27.7V200H106v-23.9h27.7V200H145v-23.9h31.2V145
h24.6v-11.3h-24.6V106H200.8z M164.8,164.7h-129V35.8h129V164.7z"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 832 B

View File

@ -0,0 +1 @@
<?xml version="1.0" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg t="1571740027058" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="6556" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><defs><style type="text/css"></style></defs><path d="M637.5424 775.0144a25.088 25.088 0 0 0 25.088-25.088V398.1312a25.088 25.088 0 0 0-50.176 0v351.7952a25.088 25.088 0 0 0 25.088 25.088zM386.304 775.0144a25.088 25.088 0 0 0 25.088-25.088V398.1312a25.088 25.088 0 0 0-50.176 0v351.7952c0 13.8752 11.2128 25.088 25.088 25.088zM511.9488 775.0144a25.088 25.088 0 0 0 25.088-25.088V398.1312a25.088 25.088 0 0 0-50.176 0v351.7952c0 13.8752 11.2128 25.088 25.088 25.088z" fill="#d7dae0" p-id="6557"></path><path d="M888.8832 251.648h-167.168V199.3216c0-34.2016-27.8528-62.0544-62.0544-62.0544H364.3392c-16.5888 0-32.1536 6.4512-43.8784 18.176a61.7472 61.7472 0 0 0-18.2272 43.8784v52.3264H135.0656a25.088 25.088 0 0 0 0 50.176H210.432v559.8208c0 13.7728 11.1616 25.088 25.088 25.088h552.8576a25.088 25.088 0 0 0 25.088-25.088V301.824h75.3664a25.1392 25.1392 0 0 0 0.0512-50.176zM346.2144 199.3216c0-4.8128 1.8944-9.3696 5.2736-12.8a18.2784 18.2784 0 0 1 12.8512-5.2736h295.3216c9.984 0 18.0736 8.1408 18.0736 18.0736v52.3264h-15.0016v-0.1024H361.216v0.1024h-15.0016V199.3216z m416.9728 637.1328H260.7104V301.824h502.4768v534.6304z" fill="#d7dae0" p-id="6558"></path></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><style>.st0{opacity:0}.st0,.st1{fill:#2d2d30}.st2{fill:#c5c5c5}.st3{fill:#2b282e}</style><g id="outline"><path class="st0" d="M0 0h16v16H0z"/><path class="st1" d="M9.586 16L8 14.414 6.414 16H1.586L0 14.414v-3.828L1.586 9H3.53l1.333-2h-.278L3 5.414V1.586L4.585 0h6.829L13 1.586v3.828L11.414 7h-.278l1.334 2h1.944L16 10.586v3.828L14.414 16H9.586zM8 10.586l1.152-1.152L8 7.705 6.847 9.434 8 10.586z"/></g><path class="st2" d="M14 10h-2.065L9.268 6H11l1-1V2l-1-1H5L4 2v3l1 1h1.733l-2.667 4H2l-1 1v3l1 1h4l1-1v-3l-1-1h-.732l2.667-4h.131l2.667 4H10l-1 1v3l1 1h4l1-1v-3l-1-1zm-8 1v3H2v-3h4zM5 5V2h6v3H5zm9 9h-4v-3h4v3z" id="icon_x5F_bg"/><path class="st3" d="M14 11v3h-4v-3h4zM2 14h4v-3H2v3zm9-12H5v3h6V2z" id="icon_x5F_fg"/></svg>

After

Width:  |  Height:  |  Size: 784 B

View File

@ -0,0 +1 @@
<?xml version="1.0" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg t="1571655529296" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="3211" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><defs><style type="text/css"></style></defs><path d="M605.333333 772.672L533.333333 830.272V533.333333a21.333333 21.333333 0 0 0-42.666666 0v296.938667l-72-57.6a21.333333 21.333333 0 0 0-26.666667 33.322667l106.666667 85.333333a21.376 21.376 0 0 0 26.666666 0l106.666667-85.333333a21.333333 21.333333 0 1 0-26.666667-33.322667z" fill="#d7dae0" p-id="3212"></path><path d="M810.666667 384c-1.130667 0-2.24 0-3.328 0.042667a298.496 298.496 0 0 0-565.418667-84.906667A213.333333 213.333333 0 0 0 256 725.333333h21.333333a21.333333 21.333333 0 0 0 0-42.666666h-21.333333a170.666667 170.666667 0 0 1 0-341.333334 21.333333 21.333333 0 0 0 19.712-13.12 255.786667 255.786667 0 0 1 491.370667 80.832 21.333333 21.333333 0 0 0 24.533333 19.626667A124.224 124.224 0 0 1 810.666667 426.666667a128 128 0 0 1 0 256h-64a21.333333 21.333333 0 0 0 0 42.666666h64a170.666667 170.666667 0 0 0 0-341.333333z" fill="#d7dae0" p-id="3213"></path></svg>

After

Width:  |  Height:  |  Size: 1.2 KiB

View File

@ -0,0 +1 @@
<?xml version="1.0" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg t="1571734698018" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="4905" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><defs><style type="text/css"></style></defs><path d="M512 99.254857a408.064 408.064 0 0 1 121.490286 18.249143c34.194286 10.605714 65.828571 24.905143 94.902857 42.861714a411.209143 411.209143 0 0 1 79.981714 64.768 409.965714 409.965714 0 0 1 61.696 82.322286c16.859429 29.659429 30.025143 61.878857 39.497143 96.658286 9.472 34.779429 14.226286 70.4 14.189714 106.861714s-4.754286 72.118857-14.189714 106.861714c-9.435429 34.742857-22.601143 66.962286-39.497143 96.658286a413.805714 413.805714 0 0 1-61.696 82.322286 410.404571 410.404571 0 0 1-79.981714 64.768c-29.110857 17.956571-60.708571 32.256-94.902857 42.861714A406.016 406.016 0 0 1 512 922.697143a408.064 408.064 0 0 1-121.490286-18.249143c-34.194286-10.605714-65.828571-24.905143-94.902857-42.861714s-55.698286-39.570286-79.981714-64.768a409.965714 409.965714 0 0 1-61.696-82.322286 415.707429 415.707429 0 0 1-39.497143-96.658286 403.309714 403.309714 0 0 1-14.189714-106.861714c0.036571-36.498286 4.754286-72.118857 14.189714-106.861714s22.601143-66.962286 39.497143-96.658286c16.896-29.659429 37.449143-57.124571 61.696-82.322286s50.907429-46.774857 79.981714-64.768c29.110857-17.956571 60.708571-32.256 94.902857-42.861714A406.272 406.272 0 0 1 512 99.254857zM322.742857 542.976H170.752c7.936 70.948571 35.254857 139.373714 81.956571 193.024s104.118857 89.417143 172.288 107.300571c-25.856-39.131429-48.347429-83.492571-67.510857-133.083428-19.2-49.517714-30.793143-109.385143-34.742857-167.241143z m307.821714 0h-237.129142c2.084571 26.697143 6.4 61.44 12.982857 88.137143 6.582857 26.697143 13.933714 50.322286 22.052571 70.875428 8.155429 20.553143 17.517714 40.850286 28.16 60.854858 10.642286 20.004571 20.224 36.498286 28.781714 49.408 8.557714 12.909714 17.444571 25.344 26.587429 37.229714 9.179429-11.885714 18.029714-24.356571 26.587429-37.412572 8.557714-13.056 18.139429-29.586286 28.781714-49.554285 10.642286-20.004571 20.041143-40.265143 28.16-60.854857s15.469714-44.141714 22.052571-70.729143c6.582857-26.514286 10.934857-61.220571 12.982857-87.954286z m-205.568-364.288c-68.169143 17.883429-125.622857 53.650286-172.288 107.264s-74.020571 123.904-81.956571 194.852571h151.990857a626.395429 626.395429 0 0 1 102.253714-302.153142v0.036571z m428.251429 364.288h-151.734857a625.444571 625.444571 0 0 1-102.546286 300.361143c68.169143-17.883429 125.586286-53.650286 172.288-107.300572a335.067429 335.067429 0 0 0 81.956572-186.843428l0.036571-6.217143zM512 172.544c-9.179429 11.885714-17.993143 24.356571-26.441143 37.412571-8.448 13.056-18.029714 29.586286-28.781714 49.554286s-20.187429 40.265143-28.306286 60.854857-15.469714 44.141714-22.052571 70.729143c-6.582857 26.550857-10.934857 62.976-12.982857 89.709714h237.129142c-2.084571-26.697143-6.4-63.195429-12.982857-89.892571-6.582857-26.697143-13.933714-50.322286-22.052571-70.875429a603.026286 603.026286 0 0 0-28.16-60.854857 610.596571 610.596571 0 0 0-28.781714-49.408A651.373714 651.373714 0 0 0 512 172.544z m87.003429 6.144a632.173714 632.173714 0 0 1 102.546285 302.116571h151.734857c-7.936-70.948571-35.254857-141.165714-81.956571-194.816-46.701714-53.650286-104.118857-89.417143-172.288-107.300571h-0.036571z" p-id="4906" fill="#d7dae0"></path></svg>

After

Width:  |  Height:  |  Size: 3.4 KiB

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"><path d="M13.451 5.609l-.579-.939-1.068.812-.076.094c-.335.415-.927 1.341-1.124 2.876l-.021.165.033.163.071.345c0 1.654-1.346 3-3 3-.795 0-1.545-.311-2.107-.868-.563-.567-.873-1.317-.873-2.111 0-1.431 1.007-2.632 2.351-2.929v2.926s2.528-2.087 2.984-2.461h.012l3.061-2.582-4.919-4.1h-1.137v2.404c-3.429.318-6.121 3.211-6.121 6.721 0 1.809.707 3.508 1.986 4.782 1.277 1.282 2.976 1.988 4.784 1.988 3.722 0 6.75-3.028 6.75-6.75 0-1.245-.349-2.468-1.007-3.536z" fill="#2D2D30"/><path d="M12.6 6.134l-.094.071c-.269.333-.746 1.096-.91 2.375.057.277.092.495.092.545 0 2.206-1.794 4-4 4-1.098 0-2.093-.445-2.817-1.164-.718-.724-1.163-1.718-1.163-2.815 0-2.206 1.794-4 4-4l.351.025v1.85s1.626-1.342 1.631-1.339l1.869-1.577-3.5-2.917v2.218l-.371-.03c-3.176 0-5.75 2.574-5.75 5.75 0 1.593.648 3.034 1.695 4.076 1.042 1.046 2.482 1.694 4.076 1.694 3.176 0 5.75-2.574 5.75-5.75-.001-1.106-.318-2.135-.859-3.012z" fill="#C5C5C5"/></svg>

After

Width:  |  Height:  |  Size: 986 B

11
resources/kendryte.svg Normal file
View File

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 23.0.3, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg version="1.1" id="图层_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 24 24" style="enable-background:new 0 0 24 24;" xml:space="preserve">
<style type="text/css">
.st0{fill:#249EDC;}
</style>
<path class="st0" d="M5.7,5v14h3V5H5.7z"/>
<path class="st0" d="M12.9,5L8.7,9.5l0,4.4L17,5H12.9z"/>
<path class="st0" d="M9,13.5l4.8,5.5h4L11,11.3L9,13.5z"/>
</svg>

After

Width:  |  Height:  |  Size: 565 B

1
resources/light/core.svg Normal file
View File

@ -0,0 +1 @@
<?xml version="1.0" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg t="1572350448357" class="icon" viewBox="0 0 1031 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="23567" xmlns:xlink="http://www.w3.org/1999/xlink" width="201.3671875" height="200"><defs><style type="text/css"></style></defs><path d="M1026.935541 342.815803v-57.79111h-125.925907V125.547941H741.558079V3.250514h-57.791109v122.297427H541.840471V3.250514h-57.274554v122.297427H342.689814V3.250514h-57.828906v122.297427H125.396754v159.464153H0v57.803709h125.913309v141.913899H0V542.483015h125.913309v141.951696H0v57.803708h125.913309v159.464154h159.464153v122.297427h57.79111v-122.297427H485.057273v122.297427h57.828906v-122.297427h141.9139v122.297427h57.791109v-122.297427H902.080539V742.238419h125.913309v-57.791109H902.080539V542.483015h125.913309v-57.753313H902.080539V342.815803h124.855002zM843.735079 843.407508H183.187864v-660.055859h660.547215v660.055859z m-145.013227-515.017435H328.20109v370.520763h370.520762V328.390073z" fill="#989898" p-id="23568"></path></svg>

After

Width:  |  Height:  |  Size: 1.1 KiB

View File

@ -0,0 +1 @@
<?xml version="1.0" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg t="1571740027058" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="6556" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><defs><style type="text/css"></style></defs><path d="M637.5424 775.0144a25.088 25.088 0 0 0 25.088-25.088V398.1312a25.088 25.088 0 0 0-50.176 0v351.7952a25.088 25.088 0 0 0 25.088 25.088zM386.304 775.0144a25.088 25.088 0 0 0 25.088-25.088V398.1312a25.088 25.088 0 0 0-50.176 0v351.7952c0 13.8752 11.2128 25.088 25.088 25.088zM511.9488 775.0144a25.088 25.088 0 0 0 25.088-25.088V398.1312a25.088 25.088 0 0 0-50.176 0v351.7952c0 13.8752 11.2128 25.088 25.088 25.088z" fill="#000000" p-id="6557"></path><path d="M888.8832 251.648h-167.168V199.3216c0-34.2016-27.8528-62.0544-62.0544-62.0544H364.3392c-16.5888 0-32.1536 6.4512-43.8784 18.176a61.7472 61.7472 0 0 0-18.2272 43.8784v52.3264H135.0656a25.088 25.088 0 0 0 0 50.176H210.432v559.8208c0 13.7728 11.1616 25.088 25.088 25.088h552.8576a25.088 25.088 0 0 0 25.088-25.088V301.824h75.3664a25.1392 25.1392 0 0 0 0.0512-50.176zM346.2144 199.3216c0-4.8128 1.8944-9.3696 5.2736-12.8a18.2784 18.2784 0 0 1 12.8512-5.2736h295.3216c9.984 0 18.0736 8.1408 18.0736 18.0736v52.3264h-15.0016v-0.1024H361.216v0.1024h-15.0016V199.3216z m416.9728 637.1328H260.7104V301.824h502.4768v534.6304z" fill="#000000" p-id="6558"></path></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><style>.st0{opacity:0}.st0,.st1{fill:#f6f6f6}.st2{fill:#424242}.st3{fill:#f0eff1}</style><g id="outline"><path class="st0" d="M0 0h16v16H0z"/><path class="st1" d="M9.586 16L8 14.414 6.414 16H1.586L0 14.414v-3.828L1.586 9H3.53l1.333-2h-.278L3 5.414V1.586L4.585 0h6.829L13 1.586v3.828L11.414 7h-.278l1.334 2h1.944L16 10.586v3.828L14.414 16H9.586zM8 10.586l1.152-1.152L8 7.705 6.847 9.434 8 10.586z"/></g><path class="st2" d="M14 10h-2.065L9.268 6H11l1-1V2l-1-1H5L4 2v3l1 1h1.733l-2.667 4H2l-1 1v3l1 1h4l1-1v-3l-1-1h-.732l2.667-4h.131l2.667 4H10l-1 1v3l1 1h4l1-1v-3l-1-1zm-8 1v3H2v-3h4zM5 5V2h6v3H5zm9 9h-4v-3h4v3z" id="icon_x5F_bg"/><path class="st3" d="M14 11v3h-4v-3h4zM2 14h4v-3H2v3zm9-12H5v3h6V2z" id="icon_x5F_fg"/></svg>

After

Width:  |  Height:  |  Size: 784 B

View File

@ -0,0 +1 @@
<?xml version="1.0" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg t="1571652317030" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="3037" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><defs><style type="text/css"></style></defs><path d="M605.333333 772.672L533.333333 830.272V533.333333a21.333333 21.333333 0 0 0-42.666666 0v296.938667l-72-57.6a21.333333 21.333333 0 0 0-26.666667 33.322667l106.666667 85.333333a21.376 21.376 0 0 0 26.666666 0l106.666667-85.333333a21.333333 21.333333 0 1 0-26.666667-33.322667z" fill="#2c2c2c" p-id="3038"></path><path d="M810.666667 384c-1.130667 0-2.24 0-3.328 0.042667a298.496 298.496 0 0 0-565.418667-84.906667A213.333333 213.333333 0 0 0 256 725.333333h21.333333a21.333333 21.333333 0 0 0 0-42.666666h-21.333333a170.666667 170.666667 0 0 1 0-341.333334 21.333333 21.333333 0 0 0 19.712-13.12 255.786667 255.786667 0 0 1 491.370667 80.832 21.333333 21.333333 0 0 0 24.533333 19.626667A124.224 124.224 0 0 1 810.666667 426.666667a128 128 0 0 1 0 256h-64a21.333333 21.333333 0 0 0 0 42.666666h64a170.666667 170.666667 0 0 0 0-341.333333z" fill="#2c2c2c" p-id="3039"></path></svg>

After

Width:  |  Height:  |  Size: 1.2 KiB

View File

@ -0,0 +1 @@
<?xml version="1.0" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg t="1571734698018" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="4905" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><defs><style type="text/css"></style></defs><path d="M512 99.254857a408.064 408.064 0 0 1 121.490286 18.249143c34.194286 10.605714 65.828571 24.905143 94.902857 42.861714a411.209143 411.209143 0 0 1 79.981714 64.768 409.965714 409.965714 0 0 1 61.696 82.322286c16.859429 29.659429 30.025143 61.878857 39.497143 96.658286 9.472 34.779429 14.226286 70.4 14.189714 106.861714s-4.754286 72.118857-14.189714 106.861714c-9.435429 34.742857-22.601143 66.962286-39.497143 96.658286a413.805714 413.805714 0 0 1-61.696 82.322286 410.404571 410.404571 0 0 1-79.981714 64.768c-29.110857 17.956571-60.708571 32.256-94.902857 42.861714A406.016 406.016 0 0 1 512 922.697143a408.064 408.064 0 0 1-121.490286-18.249143c-34.194286-10.605714-65.828571-24.905143-94.902857-42.861714s-55.698286-39.570286-79.981714-64.768a409.965714 409.965714 0 0 1-61.696-82.322286 415.707429 415.707429 0 0 1-39.497143-96.658286 403.309714 403.309714 0 0 1-14.189714-106.861714c0.036571-36.498286 4.754286-72.118857 14.189714-106.861714s22.601143-66.962286 39.497143-96.658286c16.896-29.659429 37.449143-57.124571 61.696-82.322286s50.907429-46.774857 79.981714-64.768c29.110857-17.956571 60.708571-32.256 94.902857-42.861714A406.272 406.272 0 0 1 512 99.254857zM322.742857 542.976H170.752c7.936 70.948571 35.254857 139.373714 81.956571 193.024s104.118857 89.417143 172.288 107.300571c-25.856-39.131429-48.347429-83.492571-67.510857-133.083428-19.2-49.517714-30.793143-109.385143-34.742857-167.241143z m307.821714 0h-237.129142c2.084571 26.697143 6.4 61.44 12.982857 88.137143 6.582857 26.697143 13.933714 50.322286 22.052571 70.875428 8.155429 20.553143 17.517714 40.850286 28.16 60.854858 10.642286 20.004571 20.224 36.498286 28.781714 49.408 8.557714 12.909714 17.444571 25.344 26.587429 37.229714 9.179429-11.885714 18.029714-24.356571 26.587429-37.412572 8.557714-13.056 18.139429-29.586286 28.781714-49.554285 10.642286-20.004571 20.041143-40.265143 28.16-60.854857s15.469714-44.141714 22.052571-70.729143c6.582857-26.514286 10.934857-61.220571 12.982857-87.954286z m-205.568-364.288c-68.169143 17.883429-125.622857 53.650286-172.288 107.264s-74.020571 123.904-81.956571 194.852571h151.990857a626.395429 626.395429 0 0 1 102.253714-302.153142v0.036571z m428.251429 364.288h-151.734857a625.444571 625.444571 0 0 1-102.546286 300.361143c68.169143-17.883429 125.586286-53.650286 172.288-107.300572a335.067429 335.067429 0 0 0 81.956572-186.843428l0.036571-6.217143zM512 172.544c-9.179429 11.885714-17.993143 24.356571-26.441143 37.412571-8.448 13.056-18.029714 29.586286-28.781714 49.554286s-20.187429 40.265143-28.306286 60.854857-15.469714 44.141714-22.052571 70.729143c-6.582857 26.550857-10.934857 62.976-12.982857 89.709714h237.129142c-2.084571-26.697143-6.4-63.195429-12.982857-89.892571-6.582857-26.697143-13.933714-50.322286-22.052571-70.875429a603.026286 603.026286 0 0 0-28.16-60.854857 610.596571 610.596571 0 0 0-28.781714-49.408A651.373714 651.373714 0 0 0 512 172.544z m87.003429 6.144a632.173714 632.173714 0 0 1 102.546285 302.116571h151.734857c-7.936-70.948571-35.254857-141.165714-81.956571-194.816-46.701714-53.650286-104.118857-89.417143-172.288-107.300571h-0.036571z" p-id="4906" fill="#000000"></path></svg>

After

Width:  |  Height:  |  Size: 3.4 KiB

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"><path d="M13.451 5.609l-.579-.939-1.068.812-.076.094c-.335.415-.927 1.341-1.124 2.876l-.021.165.033.163.071.345c0 1.654-1.346 3-3 3-.795 0-1.545-.311-2.107-.868-.563-.567-.873-1.317-.873-2.111 0-1.431 1.007-2.632 2.351-2.929v2.926s2.528-2.087 2.984-2.461h.012l3.061-2.582-4.919-4.1h-1.137v2.404c-3.429.318-6.121 3.211-6.121 6.721 0 1.809.707 3.508 1.986 4.782 1.277 1.282 2.976 1.988 4.784 1.988 3.722 0 6.75-3.028 6.75-6.75 0-1.245-.349-2.468-1.007-3.536z" fill="#F6F6F6"/><path d="M12.6 6.134l-.094.071c-.269.333-.746 1.096-.91 2.375.057.277.092.495.092.545 0 2.206-1.794 4-4 4-1.098 0-2.093-.445-2.817-1.164-.718-.724-1.163-1.718-1.163-2.815 0-2.206 1.794-4 4-4l.351.025v1.85s1.626-1.342 1.631-1.339l1.869-1.577-3.5-2.917v2.218l-.371-.03c-3.176 0-5.75 2.574-5.75 5.75 0 1.593.648 3.034 1.695 4.076 1.042 1.046 2.482 1.694 4.076 1.694 3.176 0 5.75-2.574 5.75-5.75-.001-1.106-.318-2.135-.859-3.012z" fill="#424242"/></svg>

After

Width:  |  Height:  |  Size: 986 B

17
resources/package.svg Normal file
View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 23.0.3, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg version="1.1" id="图层_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 50 50" style="enable-background:new 0 0 50 50;" xml:space="preserve">
<style type="text/css">
.st0{fill:#D7DAE0;}
</style>
<g>
<polygon class="st0" points="13.1,47 10.1,47 10.1,3 13.1,3 13.1,24.5 16.6,19.8 16.6,0 6.6,0 6.6,50 16.6,50 16.6,34.5 13.1,39.2
"/>
<polygon class="st0" points="16.1,30.7 13.1,34.9 13.1,39.2 16.1,35.2 16.1,35.2 18.6,31.9 16.8,29.7 "/>
<polygon class="st0" points="18.6,27.3 21.8,23 21.9,22.8 "/>
<polygon class="st0" points="24.2,24.5 24.2,24.5 22.4,22.2 21.8,23 20.4,24.8 22.3,27 38,46.9 34.2,46.9 20.4,29.4 18.6,27.3
16.8,29.7 18.6,31.9 18.6,31.9 33,50 44.5,50 "/>
<polygon class="st0" points="16.1,24.8 32.8,3 36.7,3 22.4,22.2 24.2,24.5 42.6,0 31.4,0 13.1,24.5 13.1,28.5 "/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1009 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 102 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 170 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 778 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 880 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 383 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 102 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 150 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 969 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 834 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 829 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

119
resources/schema.json Normal file
View File

@ -0,0 +1,119 @@
{
"description": "Kendryte package schema",
"definitions": {
"schemaArray": {
"type": "array",
"minItems": 1,
"items": { "$ref": "#" }
},
"positiveInteger": {
"type": "integer",
"minimum": 0
},
"positiveIntegerDefault0": {
"allOf": [ { "$ref": "#/definitions/positiveInteger" }, { "default": 0 } ]
},
"simpleTypes": {
"enum": [ "array", "boolean", "integer", "null", "number", "object", "string" ]
},
"stringArray": {
"type": "array",
"items": { "type": "string" },
"minItems": 1,
"uniqueItems": true
}
},
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "Project name"
},
"version": {
"type": "string",
"description": "Project version"
},
"type": {
"type": "string",
"enum": ["executable", "library"],
"description": "Project type. 'executable', 'library' can be selected."
},
"dependencies": {
"type": "object",
"description": "Dependencies of project"
},
"include": {
"type": "array",
"description": "Include a directories named 'include'"
},
"includeFolders": {
"type": "array",
"description": "Inclue a folder"
},
"source": {
"type": "array",
"description": "Source files. File wildcard character can be used."
},
"header": {
"type": "array",
"description": "CMakeLists header"
},
"homepage": {
"type": "string",
"description": "Project homepage"
},
"definitions": {
"type": "object",
"description": "Cmake target compile definitions"
},
"extraList": {
"type": "string",
"description": "Extra CMakeLists file"
},
"properties": {
"type": "object",
"description": "Cmake target compile properties"
},
"c_flags": {
"type": "array",
"description": "Set compile .c file flags"
},
"cpp_flags": {
"type": "array",
"description": "Set compile .cpp file flags"
},
"c_cpp_flags": {
"type": "array",
"description": "Set compile .c and .cpp file flags"
},
"link_flags": {
"type": "array",
"description": "Set cmake link flags"
},
"ld_file": {
"type": "string",
"description": "Set .ld file path"
},
"linkArgumentPrefix": {
"type": "array",
"description": "Set cmake link argument prefix"
},
"linkArgumentSuffix": {
"type": "array",
"description": "Set cmake link argument suffix"
},
"systemLibrary": {
"type": "array",
"description": "Set system library path"
},
"debug": {
"type": "boolean",
"description": "Set Debug mode"
}
},
"dependencies": {
"exclusiveMaximum": [ "maximum" ],
"exclusiveMinimum": [ "minimum" ]
},
"default": {}
}

199
scripts/build.js Normal file
View File

@ -0,0 +1,199 @@
'use strict';
// Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = 'production';
process.env.NODE_ENV = 'production';
// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', err => {
throw err;
});
// Ensure environment variables are read.
require('../config/env');
const path = require('path');
const chalk = require('react-dev-utils/chalk');
const fs = require('fs-extra');
const webpack = require('webpack');
const configFactory = require('../config/webpack.config');
const paths = require('../config/paths');
const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
const formatWebpackMessages = require('react-dev-utils/formatWebpackMessages');
const printHostingInstructions = require('react-dev-utils/printHostingInstructions');
const FileSizeReporter = require('react-dev-utils/FileSizeReporter');
const printBuildError = require('react-dev-utils/printBuildError');
const measureFileSizesBeforeBuild =
FileSizeReporter.measureFileSizesBeforeBuild;
const printFileSizesAfterBuild = FileSizeReporter.printFileSizesAfterBuild;
const useYarn = fs.existsSync(paths.yarnLockFile);
// These sizes are pretty large. We'll warn for bundles exceeding them.
const WARN_AFTER_BUNDLE_GZIP_SIZE = 512 * 1024;
const WARN_AFTER_CHUNK_GZIP_SIZE = 1024 * 1024;
const isInteractive = process.stdout.isTTY;
// Warn and crash if required files are missing
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
process.exit(1);
}
// Generate configuration
const config = configFactory('production');
// We require that you explicitly set browsers and do not fall back to
// browserslist defaults.
const { checkBrowsers } = require('react-dev-utils/browsersHelper');
checkBrowsers(paths.appPath, isInteractive)
.then(() => {
// First, read the current file sizes in build directory.
// This lets us display how much they changed later.
return measureFileSizesBeforeBuild(paths.appBuild);
})
.then(previousFileSizes => {
// Remove all content but keep the directory so that
// if you're in it, you don't end up in Trash
fs.emptyDirSync(paths.appBuild);
// Merge with the public folder
copyPublicFolder();
// Start the webpack build
return build(previousFileSizes);
})
.then(
({ stats, previousFileSizes, warnings }) => {
if (warnings.length) {
console.log(chalk.yellow('Compiled with warnings.\n'));
console.log(warnings.join('\n\n'));
console.log(
'\nSearch for the ' +
chalk.underline(chalk.yellow('keywords')) +
' to learn more about each warning.'
);
console.log(
'To ignore, add ' +
chalk.cyan('// eslint-disable-next-line') +
' to the line before.\n'
);
} else {
console.log(chalk.green('Compiled successfully.\n'));
}
console.log('File sizes after gzip:\n');
printFileSizesAfterBuild(
stats,
previousFileSizes,
paths.appBuild,
WARN_AFTER_BUNDLE_GZIP_SIZE,
WARN_AFTER_CHUNK_GZIP_SIZE
);
console.log();
const appPackage = require(paths.appPackageJson);
const publicUrl = paths.publicUrl;
const publicPath = config.output.publicPath;
const buildFolder = path.relative(process.cwd(), paths.appBuild);
printHostingInstructions(
appPackage,
publicUrl,
publicPath,
buildFolder,
useYarn
);
},
err => {
const tscCompileOnError = process.env.TSC_COMPILE_ON_ERROR === 'true';
if (tscCompileOnError) {
console.log(chalk.yellow(
'Compiled with the following type errors (you may want to check these before deploying your app):\n'
));
printBuildError(err);
} else {
console.log(chalk.red('Failed to compile.\n'));
printBuildError(err);
process.exit(1);
}
}
)
.catch(err => {
if (err && err.message) {
console.log(err.message);
}
process.exit(1);
});
// Create the production build and print the deployment instructions.
function build(previousFileSizes) {
// We used to support resolving modules according to `NODE_PATH`.
// This now has been deprecated in favor of jsconfig/tsconfig.json
// This lets you use absolute paths in imports inside large monorepos:
if (process.env.NODE_PATH) {
console.log(
chalk.yellow(
'Setting NODE_PATH to resolve modules absolutely has been deprecated in favor of setting baseUrl in jsconfig.json (or tsconfig.json if you are using TypeScript) and will be removed in a future major release of create-react-app.'
)
);
console.log();
}
console.log('Creating an optimized production build...');
const compiler = webpack(config);
return new Promise((resolve, reject) => {
compiler.run((err, stats) => {
let messages;
if (err) {
if (!err.message) {
return reject(err);
}
messages = formatWebpackMessages({
errors: [err.message],
warnings: [],
});
} else {
messages = formatWebpackMessages(
stats.toJson({ all: false, warnings: true, errors: true })
);
}
if (messages.errors.length) {
// Only keep the first error. Others are often indicative
// of the same problem, but confuse the reader with noise.
if (messages.errors.length > 1) {
messages.errors.length = 1;
}
return reject(new Error(messages.errors.join('\n\n')));
}
if (
process.env.CI &&
(typeof process.env.CI !== 'string' ||
process.env.CI.toLowerCase() !== 'false') &&
messages.warnings.length
) {
console.log(
chalk.yellow(
'\nTreating warnings as errors because process.env.CI = true.\n' +
'Most CI servers set it automatically.\n'
)
);
return reject(new Error(messages.warnings.join('\n\n')));
}
return resolve({
stats,
previousFileSizes,
warnings: messages.warnings,
});
});
});
}
function copyPublicFolder() {
fs.copySync(paths.appPublic, paths.appBuild, {
dereference: true,
filter: file => file !== paths.appHtml,
});
}

148
scripts/start.js Normal file
View File

@ -0,0 +1,148 @@
'use strict';
// Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = 'development';
process.env.NODE_ENV = 'development';
process.env.HTTPS = 'true';
// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', err => {
throw err;
});
// Ensure environment variables are read.
require('../config/env');
const fs = require('fs');
const chalk = require('react-dev-utils/chalk');
const webpack = require('webpack');
const WebpackDevServer = require('webpack-dev-server');
const clearConsole = require('react-dev-utils/clearConsole');
const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
const {
choosePort,
createCompiler,
prepareProxy,
prepareUrls,
} = require('react-dev-utils/WebpackDevServerUtils');
const openBrowser = require('react-dev-utils/openBrowser');
const paths = require('../config/paths');
const configFactory = require('../config/webpack.config');
const createDevServerConfig = require('../config/webpackDevServer.config');
const useYarn = fs.existsSync(paths.yarnLockFile);
const isInteractive = process.stdout.isTTY;
// Warn and crash if required files are missing
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
process.exit(1);
}
// Tools like Cloud9 rely on this.
const DEFAULT_PORT = parseInt(process.env.PORT, 10) || 4396;
const HOST = process.env.HOST || '0.0.0.0';
if (process.env.HOST) {
console.log(
chalk.cyan(
`Attempting to bind to HOST environment variable: ${chalk.yellow(
chalk.bold(process.env.HOST)
)}`
)
);
console.log(
`If this was unintentional, check that you haven't mistakenly set it in your shell.`
);
console.log(
`Learn more here: ${chalk.yellow('https://bit.ly/CRA-advanced-config')}`
);
console.log();
}
// We require that you explicitly set browsers and do not fall back to
// browserslist defaults.
const { checkBrowsers } = require('react-dev-utils/browsersHelper');
checkBrowsers(paths.appPath, isInteractive)
.then(() => {
// We attempt to use the default port but if it is busy, we offer the user to
// run on a different port. `choosePort()` Promise resolves to the next free port.
return choosePort(HOST, DEFAULT_PORT);
})
.then(port => {
if (port == null) {
// We have not found a port.
return;
}
const config = configFactory('development');
const protocol = process.env.HTTPS === 'true' ? 'https' : 'http';
const appName = require(paths.appPackageJson).name;
const useTypeScript = fs.existsSync(paths.appTsConfig);
const tscCompileOnError = process.env.TSC_COMPILE_ON_ERROR === 'true';
const urls = prepareUrls(protocol, HOST, port);
const devSocket = {
warnings: warnings =>
devServer.sockWrite(devServer.sockets, 'warnings', warnings),
errors: errors =>
devServer.sockWrite(devServer.sockets, 'errors', errors),
};
// Create a webpack compiler that is configured with custom messages.
const compiler = createCompiler({
appName,
config,
devSocket,
urls,
useYarn,
useTypeScript,
tscCompileOnError,
webpack,
});
// Load proxy config
const proxySetting = require(paths.appPackageJson).proxy;
const proxyConfig = prepareProxy(proxySetting, paths.appPublic);
// Serve webpack assets generated by the compiler over a web server.
const serverConfig = createDevServerConfig(
proxyConfig,
urls.lanUrlForConfig
);
const devServer = new WebpackDevServer(compiler, serverConfig);
// Launch WebpackDevServer.
devServer.listen(port, HOST, err => {
if (err) {
return console.log(err);
}
if (isInteractive) {
clearConsole();
}
// We used to support resolving modules according to `NODE_PATH`.
// This now has been deprecated in favor of jsconfig/tsconfig.json
// This lets you use absolute paths in imports inside large monorepos:
if (process.env.NODE_PATH) {
console.log(
chalk.yellow(
'Setting NODE_PATH to resolve modules absolutely has been deprecated in favor of setting baseUrl in jsconfig.json (or tsconfig.json if you are using TypeScript) and will be removed in a future major release of create-react-app.'
)
);
console.log();
}
console.log(chalk.cyan('Starting the development server...\n'));
openBrowser(urls.localUrlForBrowser);
});
['SIGINT', 'SIGTERM'].forEach(function(sig) {
process.on(sig, function() {
devServer.close();
process.exit();
});
});
})
.catch(err => {
if (err && err.message) {
console.log(err.message);
}
process.exit(1);
});

53
scripts/test.js Normal file
View File

@ -0,0 +1,53 @@
'use strict';
// Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = 'test';
process.env.NODE_ENV = 'test';
process.env.PUBLIC_URL = '';
// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', err => {
throw err;
});
// Ensure environment variables are read.
require('../config/env');
const jest = require('jest');
const execSync = require('child_process').execSync;
let argv = process.argv.slice(2);
function isInGitRepository() {
try {
execSync('git rev-parse --is-inside-work-tree', { stdio: 'ignore' });
return true;
} catch (e) {
return false;
}
}
function isInMercurialRepository() {
try {
execSync('hg --cwd . root', { stdio: 'ignore' });
return true;
} catch (e) {
return false;
}
}
// Watch unless on CI or explicitly running all tests
if (
!process.env.CI &&
argv.indexOf('--watchAll') === -1 &&
argv.indexOf('--watchAll=false') === -1
) {
// https://github.com/facebook/create-react-app/issues/5210
const hasSourceControl = isInGitRepository() || isInMercurialRepository();
argv.push(hasSourceControl ? '--watch' : '--watchAll');
}
jest.run(argv);

View File

@ -0,0 +1,63 @@
import * as vscode from 'vscode'
import { readFilePromisify, writeFilePromisify, urlJoin } from '@utils/index'
import { installPackage } from '@common/dependency'
import { localDependenciesReader } from '@common/local-dependencies'
import * as path from 'path'
import Axios from 'axios'
import { DevPackages } from '@treeview/DevPackages'
export const addDependency = (context: vscode.ExtensionContext, depProvider: DevPackages): vscode.Disposable => {
return vscode.commands.registerCommand('extension.addDependency', packageName => {
return new Promise(async (resolve, reject) => {
const hostConfig = JSON.parse(await readFilePromisify(`${context.extensionPath}/config.json`, 'utf8'))
const remoteHost = hostConfig.host
Axios({
method: 'get',
url: urlJoin(remoteHost, 'package', 'list.json'),
responseType: 'json'
})
.then(res => {
if (!vscode.workspace.rootPath) {
reject('Please open a workspace')
return
}
/*
To do..
Add quick pick if packageName is undefined.
*/
const remotePackages = res.data.packages
if (!remotePackages[packageName]) {
reject(`Cannot find module ${packageName} on server.`)
return
}
const configPath = path.join(vscode.workspace.rootPath, 'kendryte-package.json')
readFilePromisify(configPath, 'utf-8')
.then(data => {
const config = JSON.parse(data)
config.dependencies[packageName] = '0.1.0'
writeFilePromisify(configPath, JSON.stringify(config, null, '\t'), 'utf-8')
.then(async res => {
const localDependencies = await localDependenciesReader()
await installPackage(
packageName,
'0.1.0',
<string>vscode.workspace.rootPath,
remotePackages,
remoteHost,
localDependencies || {}
)
vscode.window.showInformationMessage(`${packageName} installed.`)
depProvider.refresh()
await vscode.commands.executeCommand('extension.configGenerate')
resolve()
})
})
.catch(error => {
reject('Kendryte-package.json is not exists.')
})
})
})
})
}

31
src/command/build.ts Normal file
View File

@ -0,0 +1,31 @@
import * as vscode from 'vscode'
import { readdirPromisify } from '@utils/index'
export const build = (context: vscode.ExtensionContext): vscode.Disposable => {
return vscode.commands.registerCommand('extension.build', async () => {
return new Promise(async (resolve, reject) => {
if (!vscode.workspace.rootPath) {
vscode.window.showErrorMessage('Please open a kendryte workspace')
return
}
readdirPromisify(vscode.workspace.rootPath)
.then(async items => {
if (!items.includes('kendryte_libraries')) {
await vscode.commands.executeCommand('packageDependencies.download')
}
await vscode.commands.executeCommand('extension.cmakelistGenerate')
const tasks = await vscode.tasks.fetchTasks()
for (const task of tasks) {
if (task.name === 'Build') {
await vscode.tasks.executeTask(task)
vscode.tasks.onDidEndTaskProcess(event => {
vscode.window.showInformationMessage('Build complete')
resolve()
})
break
}
}
})
})
})
}

View File

@ -0,0 +1,57 @@
import * as vscode from 'vscode'
import { projectConfigParser } from '@common/project-config-parser'
import { ProjectConfig } from '@command/makefileService/types'
import { systemFilter, writeFilePromisify } from '@utils/index'
import { join } from 'path'
export const createCCppConfig = async (): Promise<void> => {
if (!vscode.workspace.rootPath) {
vscode.window.showErrorMessage('Please open a workspace.')
return
}
const config = await projectConfigParser(vscode.workspace.rootPath)
if (!config) {
vscode.window.showErrorMessage('Please open a kendryte workspace')
return
}
const data = createConfig(config)
await writeFilePromisify(join(vscode.workspace.rootPath, '.vscode/c_cpp_properties.json'), JSON.stringify(data, null, 4), {
mode: 0o777,
encoding: 'utf-8'
})
}
const createConfig = (config: ProjectConfig): any => {
const includePath: Array<string> = []
const packagePath = (process.env.packagePath || '').replace(/\\/g, '/')
const toolchainList = [
'toolchain/riscv64-unknown-elf/include',
'toolchain/lib/gcc/riscv64-unknown-elf/8.2.0/include',
'toolchain/lib/gcc/riscv64-unknown-elf/8.2.0/include-fixed',
'toolchain/riscv64-unknown-elf/include/c++/8.2.0',
'toolchain/riscv64-unknown-elf/include/c++/8.2.0/riscv64-unknown-elf',
]
toolchainList.map(item => {
includePath.push(join(packagePath, item).replace(/\\/g, '/'))
})
if (config.includeFolders) {
config.includeFolders.map(include => {
includePath.push(join(<string>vscode.workspace.rootPath, include).replace(/\\/g, '/'))
})
}
const data = {
version: 4,
configurations: [
{
name: "Default",
defines: [],
compilerPath: systemFilter(join(packagePath, 'toolchain/bin/riscv64-unknown-elf-g++.exe').replace(/\\/g, '/'), join(packagePath, 'toolchain/bin/riscv64-unknown-elf-g++'), join(packagePath, 'toolchain/bin/riscv64-unknown-elf-g++')),
cStandard: "c11",
cppStandard: "c++17",
intelliSenseMode: "gcc-x64",
includePath: includePath
}
]
}
return data
}

View File

@ -0,0 +1,40 @@
import * as vscode from 'vscode'
import { cpus } from 'os'
import { writeFilePromisify, format, systemFilter } from '@utils/index'
import { join } from 'path'
export const createCmakeConfig = async () => {
const data = systemFilter(createWindowsCmakeDefaultConfig(), createUnixCmakeDefaultConfig(), createUnixCmakeDefaultConfig())
await writeFilePromisify(systemFilter(`${vscode.workspace.rootPath}/.vscode/cmake.cmd`, `${vscode.workspace.rootPath}/.vscode/cmake.sh`, `${vscode.workspace.rootPath}/.vscode/cmake.sh`), data, {mode: 0o777})
}
const createUnixCmakeDefaultConfig = ():string => {
if (!process.env.packagePath) {
vscode.window.showErrorMessage('No local dependencies found. Please try to execute reinsall packages command.')
return ''
}
return format(`
# This is build script.
# Do not modify this file unless you know what are you doing!
\nmkdir ${vscode.workspace.rootPath}/build
cd ${vscode.workspace.rootPath}/build
export PATH=${join(process.env.packagePath, 'toolchain/bin')}:$PATH
${join(process.env.packagePath, 'cmake/bin/cmake')} .. && ${join(process.env.packagePath, 'cmake/bin/cmake')} --build ${vscode.workspace.rootPath}/build -- -j ${cpus().length - 1 <= 0 ? 2 : cpus().length - 1}
`)
}
const createWindowsCmakeDefaultConfig = ():string => {
if (!process.env.packagePath) {
vscode.window.showErrorMessage('No local dependencies found. Please try to execute reinsall packages command.')
return ''
}
return format(`
:: This is build script.
:: Do not modify this file unless you know what are you doing!
\nmkdir ${vscode.workspace.rootPath}\\build
cd ${vscode.workspace.rootPath}\\build
set Path=${join(process.env.packagePath, 'toolchain/bin')};${process.env.Path}
set CMAKE_MAKE_PROGRAM=make
${join(process.env.packagePath, 'cmake/bin/cmake.exe')} -G "Unix Makefiles" .. && ${join(process.env.packagePath, 'cmake/bin/cmake.exe')} --build ${vscode.workspace.rootPath}\\build -- -j ${cpus().length - 1 <= 0 ? 2 : cpus().length - 1}
`)
}

View File

@ -0,0 +1,91 @@
import * as vscode from 'vscode'
import { writeFilePromisify, format, systemFilter } from '@utils/index'
import { projectConfigParser } from '@common/index'
import { join } from 'path'
export const createDebugConfigFile = (port: number): void => {
createLaunchConfig(port)
createTasksConfig()
}
const createLaunchConfig = async (port: number): Promise<void> => {
if (!vscode.workspace.rootPath) {
vscode.window.showErrorMessage('Please open a workspace.')
return
}
const config = await projectConfigParser(vscode.workspace.rootPath)
if (!config) {
vscode.window.showErrorMessage('Please open a kendryte workspace.')
return
}
const projectName = config.name
const data = createDefaultLaunchConfig(projectName, port)
await writeFilePromisify(`${vscode.workspace.rootPath}/.vscode/launch.json`, data)
}
const createDefaultLaunchConfig = (projectName: string, port: number): string => {
if (!process.env.packagePath) {
return ''
}
const packagePath = process.env.packagePath.replace(/\\/g, '/')
return format(`
{
"$schema": "vscode://schemas/launch",
"version": "0.2.0",
"configurations": [
{
"id": "kendryte",
"type": "kendryte",
"request": "launch",
"name": "KDBG",
"executable": "${join(vscode.workspace.rootPath || '', 'build', projectName). replace(/\\/g, '/')}",
"target": "127.0.0.1:${port}",
"cwd": "${join(vscode.workspace.rootPath || '', 'build'). replace(/\\/g, '/')}",
"internalConsoleOptions": "openOnSessionStart",
"env": {
"PATH": "${join(packagePath, 'toolchain/bin').replace(/\\/g, '/')}:${join(packagePath, 'cmake/bin/').replace(/\\/g, '/')}:${join(packagePath, 'jlink').replace(/\\/g, '/')}:${join(packagePath, 'clang-format/bin').replace(/\\/g, '/')}:${join(process.env.PATH || '').replace(/\\/g, '/')}",
"Path": "${join(packagePath, 'toolchain/bin').replace(/\\/g, '/')};${join(packagePath, 'cmake/bin/').replace(/\\/g, '/')};${join(packagePath, 'jlink').replace(/\\/g, '/')};${join(packagePath, 'clang-format/bin').replace(/\\/g, '/')};${join(process.env.PATH || '').replace(/\\/g, '/')}",
},
"autorun": [],
"gdbpath": "${join(packagePath, 'toolchain/bin/riscv64-unknown-elf-gdb').replace(/\\/g, '/')}",
"preLaunchTask": "Start Openocd and Build"
}
]
}
` + '\n')
}
const createTasksConfig = async (): Promise<void> => {
const data = createDefaultTasksConfig()
await writeFilePromisify(`${vscode.workspace.rootPath}/.vscode/tasks.json`, data)
}
const createDefaultTasksConfig = ():string => {
return format(`
{
"version": "2.0.0",
"tasks": [
{
"label": "Build",
"command": "${systemFilter('.vscode/cmake.cmd', `${vscode.workspace.rootPath}/.vscode/cmake.sh`, `${vscode.workspace.rootPath}/.vscode/cmake.sh`)}",
"type": "process",
"presentation": {
"reveal": "always"
},
"group": {
"kind": "build",
"isDefault": true
}
},
{
"label": "Start Openocd",
"command": "\${command:extension.openocd.restart}"
},
{
"label": "Start Openocd and Build",
"dependsOn":["Build", "Start Openocd"]
}
]
}
` + '\n')
}

View File

@ -0,0 +1,47 @@
import * as vscode from 'vscode'
import { createServer, AddressInfo } from 'net'
import { createOpenocdConfigFile } from '@command/configGenerate/openocdConfig'
import { createDebugConfigFile } from '@command/configGenerate/debugConfig'
import { createCmakeConfig } from '@command/configGenerate/cmake'
import { createCCppConfig } from '@command/configGenerate/c-cpp-config'
import * as fs from 'fs'
import { join } from 'path'
// Find openocd service port
const findPort = (): Promise<number> => {
return new Promise(resolve => {
let port: number = vscode.workspace.getConfiguration('openocd').get('port') || 0
if (port === 0) {
const s = createServer()
s.listen(0, () => {
const port = (s.address() as AddressInfo).port
s.close(() => {
resolve(port)
})
})
} else resolve(port)
})
}
// VSCode command register
export const configGenerate = (): vscode.Disposable => {
return vscode.commands.registerCommand('extension.configGenerate', () => {
return new Promise(async (resolve, reject) => {
const port = await findPort()
if (!vscode.workspace.rootPath) {
vscode.window.showErrorMessage('Please open a kendryte folder.')
return
}
try {
fs.mkdirSync(join(vscode.workspace.rootPath, '.vscode'))
} catch(e) {
console.log(e)
}
createOpenocdConfigFile(port)
createDebugConfigFile(port)
createCmakeConfig()
createCCppConfig()
resolve()
})
})
}

View File

@ -0,0 +1,86 @@
import * as vscode from 'vscode'
import { format, writeFilePromisify } from '@utils/index'
import { JTagConfigExtra, FtdiConfigExtra } from '@command/configGenerate/types'
export const createOpenocdConfigFile = async (port: number): Promise<void> => {
const data = await createConfigContent(port)
await writeFilePromisify(`${vscode.workspace.rootPath}/.vscode/openocd.cfg`, data)
// this.logger.info('config file write to: ' + `${vscode.workspace.rootPath}/.vscode/openocd.cfg`)
}
const createConfigContent = async (port: number): Promise<string> => {
const type = vscode.workspace.getConfiguration('openocd').get('useKey')
// this.logger.info('port=' + port)
let serialNumber: number = vscode.workspace.getConfiguration('JTag').get('ID') || 0
switch (type) {
case 'JTag':
return await createDefaultJTagConfig(port, {
speed: vscode.workspace.getConfiguration('JTag').get('speed') || 30000,
serialNumber,
})
case 'FTDI':
return await createDefaultFtdiConfig(port, {
speed: vscode.workspace.getConfiguration('FTDI').get('speed') || 25000,
layoutInit: vscode.workspace.getConfiguration('FTDI').get('layout') || '00e8 00eb',
vidPid: vscode.workspace.getConfiguration('FTDI').get('vid_pid') || '0403 6014',
tdoSampleFallingEdge: vscode.workspace.getConfiguration('FTDI').get('tdo-fe') || true
})
default:
return await createDefaultJTagConfig(port, {
speed: vscode.workspace.getConfiguration('JTag').get('speed') || 30000,
serialNumber,
})
}
}
// Openocd config generator
const createDefaultJTagConfig = (port: number, options: JTagConfigExtra): string => {
return format(`
# debug adapter
interface jlink
${options.serialNumber > 0 ? '' : '# '}jlink serial ${options.serialNumber}
transport select jtag
adapter_khz ${options.speed}
gdb_port ${port}
tcl_port ${port + 1}
telnet_port ${port + 2}
set _CHIPNAME riscv
jtag newtap $_CHIPNAME cpu -irlen 5 -expected-id 0x04e4796b
set _TARGETNAME $_CHIPNAME.cpu
target create $_TARGETNAME riscv -chain-position $_TARGETNAME
init
halt
` + '\n')
}
const createDefaultFtdiConfig = (port: number, config: FtdiConfigExtra): string => {
const [vid1, vid2] = config.vidPid.split(/\s/)
const [lay1, lay2] = config.layoutInit.split(/\s/)
return format(`
interface ftdi
# for canaan's ftdi
ftdi_vid_pid 0x${vid1} 0x${vid2}
ftdi_layout_init 0x${lay1} 0x${lay2}
transport select jtag
${config.tdoSampleFallingEdge ? '' : '# '}ftdi_tdo_sample_edge falling
adapter_khz 3000
gdb_port ${port}
tcl_port ${port + 1}
telnet_port ${port + 2}
set _CHIPNAME riscv
jtag newtap $_CHIPNAME cpu -irlen 5 -expected-id 0x04e4796b
set _TARGETNAME $_CHIPNAME.cpu
target create $_TARGETNAME riscv -chain-position $_TARGETNAME
$_TARGETNAME configure -event reset-start {
adapter_khz 100
}
$_TARGETNAME configure -event reset-init {
adapter_khz ${config.speed}
}
init
` + '\n')
}

View File

@ -0,0 +1,11 @@
export interface JTagConfigExtra {
speed: number
serialNumber: number
}
export interface FtdiConfigExtra {
speed: number
layoutInit: string
vidPid: string
tdoSampleFallingEdge: boolean
}

View File

@ -0,0 +1,12 @@
import * as vscode from 'vscode'
import { ReactPanel } from '@common/react-panel'
export const createHelloworld = (context: vscode.ExtensionContext): vscode.Disposable => {
return vscode.commands.registerCommand('extension.createHelloworld', async (params) => {
return new Promise(async resolve => {
vscode.tasks.fetchTasks()
.then(data => console.log(data))
resolve()
})
})
}

View File

@ -0,0 +1,10 @@
import * as vscode from 'vscode'
import { ReactPanel } from '@common/react-panel'
export const createWebview = (context: vscode.ExtensionContext): vscode.Disposable => {
return vscode.commands.registerCommand('packageDependencies.createWebview', async () => {
return new Promise(async resolve => {
ReactPanel.createOrShow(context.extensionPath, context.subscriptions)
})
})
}

7
src/command/debug.ts Normal file
View File

@ -0,0 +1,7 @@
import * as vscode from 'vscode'
export const debug = (context: vscode.ExtensionContext): vscode.Disposable => {
return vscode.commands.registerCommand('extension.debug', () => {
vscode.debug.startDebugging((vscode.workspace.workspaceFolders && vscode.workspace.workspaceFolders[0]), 'KDBG')
})
}

View File

@ -0,0 +1,34 @@
import * as vscode from 'vscode'
import { readFilePromisify, writeFilePromisify, removeDir } from '@utils/index'
import { join } from 'path'
import { DevPackages } from '@treeview/DevPackages'
export const deleteDependency = (depProvider: DevPackages) => {
return vscode.commands.registerCommand('packageDependencies.delete', treeItem => {
const packageName = treeItem.label
return new Promise((resolve, reject) => {
const workspace = vscode.workspace.rootPath
if (!workspace) {
vscode.window.showErrorMessage('Please open a workspace')
reject('Please open a workspace')
return
}
const configPath = join(workspace, 'kendryte-package.json')
readFilePromisify(configPath, 'utf-8')
.then(async data => {
const config = JSON.parse(data)
delete config.dependencies[packageName]
await writeFilePromisify(configPath, JSON.stringify(config, null, '\t'), 'utf-8')
await removeDir(join(workspace, 'kendryte_libraries', packageName))
vscode.window.showInformationMessage(`${packageName} deleted.`)
depProvider.refresh()
await vscode.commands.executeCommand('extension.configGenerate')
resolve()
})
.catch(err => {
reject('Please open a kendryte workspace.')
return
})
})
})
}

View File

@ -0,0 +1,63 @@
import * as vscode from 'vscode'
import { localDependenciesReader, projectConfigParser } from '@common/index'
import { readFileSync } from 'fs'
import { urlJoin } from '@utils/index'
import Axios from 'axios'
import { installPackage } from '@common/dependency'
export const dependenciesDownload = (context: vscode.ExtensionContext): vscode.Disposable => {
return vscode.commands.registerCommand('packageDependencies.download', async () => {
return new Promise(async (resolve, reject) => {
let localDependencies = await localDependenciesReader()
const workspacePath = vscode.workspace.rootPath
if (!workspacePath) {
reject('Please open a kendryte project folder.')
return
}
const config = await projectConfigParser(workspacePath)
if (!config) {
reject('Please open a kendryte project folder.')
return
}
const dependencies = config.dependencies
if (!dependencies || Object.keys(dependencies).length === 0) {
vscode.window.showInformationMessage('No packages found.')
return
}
const hostConfig = JSON.parse(readFileSync(`${context.extensionPath}/config.json`, 'utf8'))
const remoteHost = hostConfig.host
const packages = hostConfig.packages
Axios({
method: 'get',
url: urlJoin(remoteHost, packages, 'list.json'),
responseType: 'json'
})
.then(async res => {
for (let dependency of Object.keys(dependencies)) {
if (!localDependencies || !localDependencies.hasOwnProperty(dependency)) {
try {
localDependencies = await installPackage(
dependency,
dependencies[dependency],
workspacePath,
res.data.packages,
remoteHost,
localDependencies || {}
)
} catch (err) {
vscode.window.showErrorMessage(err)
return
}
}
}
vscode.window.showInformationMessage('Packages installed.')
await vscode.commands.executeCommand('extension.configGenerate')
resolve()
})
.catch(err => {
console.log(err)
reject(err)
})
})
})
}

14
src/command/index.ts Normal file
View File

@ -0,0 +1,14 @@
export * from '@command/reinstallpackage'
export * from '@command/build'
export * from '@command/create-helloworld-project'
export * from '@command/upload'
export * from '@command/debug'
export * from '@command/openocd'
export * from '@command/configGenerate'
export * from '@command/makefileService'
export * from '@command/pickdevice'
export * from '@command/create-webview'
export * from '@command/dependencies'
export * from '@command/add-dependency'
export * from '@command/delete-dependency'
export * from '@command/serialport'

View File

@ -0,0 +1,13 @@
import { readFileSync, readdirSync } from 'fs'
import { FileList } from '@command/makefileService/types'
import { join } from 'path'
export const fileListReader = (path: string): FileList => {
const fileList = readdirSync(path)
const reader: FileList = {}
fileList.map(filename => {
const data = readFileSync(join(path, filename), 'utf-8')
reader[filename.replace(/.cmake/,'')] = data
})
return reader
}

View File

@ -0,0 +1,28 @@
import * as vscode from 'vscode'
import { createCmakeListFile } from '@command/makefileService/writeCmakeList'
import { searchProjects } from '@command/makefileService/searchProjects'
import { ProjectInfo } from './types'
// VSCode command register
export const cmakelistGenerate = (): vscode.Disposable => {
return vscode.commands.registerCommand('extension.cmakelistGenerate', () => {
return new Promise(async (resolve, reject) => {
const projectList = await searchProjects()
if (projectList.rootProject) {
createCmakeListFile(projectList.rootProject, Object.values(projectList.dependencies))
Object.values(projectList.dependencies).map(project => {
const dependencyList = Object.keys(project.config.dependencies || {})
const dependencyConfigList: Array<ProjectInfo> = []
dependencyList.map(item => {
if (projectList.dependencies[item]) dependencyConfigList.push(projectList.dependencies[item])
})
createCmakeListFile(project, dependencyConfigList)
})
} else {
vscode.window.showErrorMessage('Please open a project folder.')
}
vscode.window.showInformationMessage('CMakeLists.txt file generated')
resolve()
})
})
}

View File

@ -0,0 +1,47 @@
import * as vscode from 'vscode'
import { readdirSync } from 'fs'
import { ProjectInfo, ProjectConfig } from '@command/makefileService/types'
import { projectConfigParser } from '@common/index'
import { join } from 'path'
interface ProjectList {
rootProject: ProjectInfo | undefined
dependencies: {
[key:string]: ProjectInfo
}
}
export const searchProjects = async (): Promise<ProjectList> => {
const packageFile = 'kendryte-package.json'
const projectList: ProjectList = {
rootProject: undefined,
dependencies: {}
}
if (!vscode.workspace.rootPath) {
return projectList
}
const rootDir = readdirSync(vscode.workspace.rootPath.replace(/\\/g, '/')) // List
if (rootDir.indexOf(packageFile) >= 0) {
const rootProjectInfo: ProjectInfo = {
path: vscode.workspace.rootPath,
isRoot: true,
config: <ProjectConfig>await projectConfigParser(vscode.workspace.rootPath)
}
projectList.rootProject = rootProjectInfo
const dependencyList = Object.keys(rootProjectInfo.config.dependencies || {})
const dependencyDir = readdirSync(`${vscode.workspace.rootPath}/kendryte_libraries`)
await Promise.all(dependencyList.map(async dependency => {
if (dependencyDir.indexOf(dependency) >= 0) {
const projectPath = join(vscode.workspace.rootPath || '', 'kendryte_libraries', dependency).replace(/\\/g, '/')
const projectInfo: ProjectInfo = {
path: projectPath,
isRoot: false,
config: <ProjectConfig>await projectConfigParser(projectPath)
}
projectList.dependencies[projectInfo.config.name] = projectInfo
}
}))
}
return projectList
}

View File

@ -0,0 +1,41 @@
export interface ProjectInfo {
path: string
isRoot: boolean
config: ProjectConfig
}
export interface ProjectConfig {
name: string
version: string
type: string
dependencies?: {
[key:string]: string
},
include?: Array<string>
includeFolders: Array<string>
source: Array<string>
header: Array<string>
homepage?: string
definitions?: {
[key: string]: any
}
extraList?: string
properties?: {
[key: string]: any
}
c_flags?: Array<string>
cpp_flags?: Array<string>
c_cpp_flags?: Array<string>
link_flags?: Array<string>
ld_file?: string
linkArgumentPrefix?: Array<string>
linkArgumentSuffix?: Array<string>
systemLibrary?: Array<string>
debug: boolean
localDependency?: Array<string>
[key: string]: any
}
export interface FileList {
[key: string]: string
}

View File

@ -0,0 +1,359 @@
import * as vscode from 'vscode'
import { writeFileSync, readFileSync } from 'fs'
import { fileListReader } from '@command/makefileService/cmakeListFileReader'
import { ProjectInfo, ProjectConfig, FileList } from '@command/makefileService/types'
import { format } from '@utils/index'
import { join } from 'path'
export const createCmakeListFile = (project: ProjectInfo, dependencies?: Array<ProjectInfo>): void => {
if (!process.env.packagePath) {
vscode.window.showErrorMessage('No local dependencies found. Please try to execute reinsall packages command.')
return
}
const fileReader = fileListReader(join(process.env.packagePath, 'cmake-list-files'))
const data = cmakeListTemplete(project.path, project.config, project.isRoot, fileReader, dependencies)
writeFileSync(`${project.path}/CMakeLists.txt`, data)
}
const cmakeListTemplete = (projectPath: string, projectConfig: ProjectConfig, isRoot: boolean, fileReader:FileList, dependencies?: Array<ProjectInfo>): string => {
return (`
# DO NOT MODIFY THIS FILE, IT WILL BE OVERRIDE!!!
# You can set the "automake" options as false on kendryte-package.json to disable auto generate CMakeLists.txt file
# [section] Head
${fileReader.reset}
cmake_minimum_required(VERSION 3.0.0)
set(PROJECT_NAME "${projectConfig.name}")
# [/section] Head
# [section] Init
${isRoot ? rootInitSection(fileReader) : '# not need in sub project'}
${debugModeProperty(projectConfig.debug)}
set(CMAKE_GENERATOR "Unix Makefiles" CACHE INTERNAL "this const is defined by toolchain")
set(CMAKE_GENERATOR_INSTANCE "" CACHE INTERNAL "this const is defined by toolchain")
# [/section] Init
# [section] Project
${fileReader.fix9985}
message("======== PROJECT:\${PROJECT_NAME} ========")
project(\${PROJECT_NAME})
## [section] Header
${includeDirs(projectConfig.header, projectConfig.includeFolders)}
## [/section] Header
## [section] Source
${sourceFiles(projectConfig.source)}
## [/section] Source
# [/section] Project
# [section] Custom
${projectConfig.extraList ? readFileSync(`${projectPath}/${projectConfig.extraList}`, 'utf-8') : ''}
# [/section] Custom
# [section] Target
${createTarget(projectConfig.type, projectConfig.source, projectConfig.name)}
${debugModeValue(projectConfig.debug)}
${setProperties(projectConfig.properties, projectConfig.definitions, dependencies)}
# [/section] Target
# [section] Dependency
${addSubProjects(isRoot, projectConfig.dependencies, projectConfig.localDependency, projectConfig.name)}
# [/section] Dependency
# [section] C/C++ compiler flags
${flags(projectConfig.c_flags, projectConfig.cpp_flags, projectConfig.c_cpp_flags)}
${linkSubProjects(isRoot, dependencies)}
# [/section] C/C++ compiler flags
# [section] Finish
${finishSection(fileReader)}
${flashable(isRoot, projectConfig.type, fileReader)}
# [/section] Finish
# [section] Dump Setting
${fileReader.dumpConfig}
${projectConfig.debug ? 'message("\n ${PROJECT_NAME} :: SOURCE_FILES=${SOURCE_FILES}")' : ''}
# [/section] Dump Setting
`)
}
const rootInitSection = (fileReader: FileList) => {
return [
fileReader.macros,
fileReader.coreFlags,
fileReader.ideSettings,
fileReader.toolchain,
].join('\n')
}
const debugModeProperty = (debug: boolean): string => {
if (!debug) {
return '# debug mode disabled'
}
return format(`
# debug mode enabled
set(-DCMAKE_VERBOSE_MAKEFILE TRUE)
set_property(GLOBAL PROPERTY JOB_POOLS single_debug=1)
`)
}
const spaceArray = (arr: Array<string>) => {
return arr.map(path => ` "\${CMAKE_CURRENT_LIST_DIR}/${path}"`).join('\n')
}
const includeDirs = (header: Array<string>, includeFolders: Array<string>): string => {
let localHeaders = '### from project local\n'
if (header && header.length) {
localHeaders += `
include_directories(
${spaceArray(header)}
)`
}
const ideHeaders = `
### from ide
include_directories("\${CMAKE_CURRENT_LIST_DIR}/config")
include_directories("\${CMAKE_CURRENT_LIST_DIR}/config/includes")
`
let sharedHeaders = '## from project public'
if (includeFolders.length) {
sharedHeaders += `
include_directories(
${spaceArray(includeFolders)}
)`
} else {
sharedHeaders += '## no headers';
}
return localHeaders + '\n' + ideHeaders + sharedHeaders
}
const sourceFiles = (source: Array<string>) => {
if (source.length > 0) {
const addSource = source.map((file) => {
return `add_source_file(${file})`;
});
return `## add source from config json (${source.length} files matched)
${addSource.join('\n')}`;
} else {
return '### project have no source code (and should not have)';
}
}
const createTarget = (type: string, source: Array<string>, name: string): string => {
const ret: Array<string> = [];
if (type === 'library') {
ret.push(`## final create ${name} library`);
if (source.length > 0) {
ret.push('add_library(${PROJECT_NAME} SHARED STATIC ${SOURCE_FILES})');
ret.push('target_compile_definitions(${PROJECT_NAME} PRIVATE "PROJECT_PATH=${CMAKE_CURRENT_LIST_DIR}/")');
} else {
ret.push('add_library(${PROJECT_NAME} SHARED STATIC IMPORTED GLOBAL)');
ret.push('set_property(TARGET ${PROJECT_NAME} PROPERTY IMPORTED_LOCATION');
// if (!this.project.json.prebuilt) {
// throw new PathAttachedError(resolvePath(this.project.path, CMAKE_CONFIG_FILE_NAME), missingJsonField('prebuilt'));
// }
// ret.push(' ' + this.spaceArray([this.project.json.prebuilt]));
ret.push(')');
}
} else {
ret.push(`## final create ${name} executable`);
ret.push('add_executable(${PROJECT_NAME} ${SOURCE_FILES})');
ret.push('target_compile_definitions(${PROJECT_NAME} PRIVATE "PROJECT_PATH=${CMAKE_CURRENT_LIST_DIR}/")');
}
return ret.join('\n');
}
const debugModeValue = (debug: boolean): string => {
if (!debug) {
return '# debug mode disabled';
}
return `# debug mode enabled
set_property(TARGET \${PROJECT_NAME} PROPERTY JOB_POOL_COMPILE single_debug)
set_property(TARGET \${PROJECT_NAME} PROPERTY JOB_POOL_LINK single_debug)`
}
const setProperties = (properties: ProjectConfig["properties"], definitions: ProjectConfig["definitions"] = {}, dependencies: Array<ProjectInfo> = []): string => {
const content = [];
if (properties && Object.keys(properties).length) {
content.push('## set properties');
for (const [key, value] of Object.entries(properties)) {
content.push(`set_target_properties($\{PROJECT_NAME} PROPERTIES ${key} ${JSON.stringify(value)})`)
}
} else {
content.push('## no properties')
}
content.push('## set definitions');
dependencies.map(item => {
Object.assign(definitions, item.config.definitions || {})
})
for (const key in definitions) {
const value = definitions[key]
const id = key.replace(/:raw/g, '')
content.push(`add_compile_definitions(${id}${value ? '=' + value : ''})`);
}
return content.join('\n');
}
const addSubProjects = (isRoot: boolean, dependencyList: ProjectConfig["dependencies"], localDependency: ProjectConfig["localDependency"], projectName: ProjectConfig["name"]): string => {
const lines = ['cmake_policy(SET CMP0079 NEW)']
if (isRoot) {
lines.push('## root project will include all dependencies')
for (const dependency in dependencyList) {
const dir = '${CMAKE_CURRENT_LIST_DIR}/kendryte_libraries/' + dependency
lines.push(`add_subdirectory("${dir}" "${dependency}")`);
}
}
if (localDependency) {
lines.push('## include local dependency')
localDependency.map(dependency => {
const dir = join('${CMAKE_CURRENT_LIST_DIR}', dependency).replace(/\\/g, '/')
lines.push(`add_subdirectory("${dir}" "${projectName}_${dependency}")`)
})
}
// Simple Folder Config
// if (this.project.directDependency.length) {
// lines.push('## add simple folder dependency');
// for (const { objectName, path, isSimpleFolder } of this.project.directDependency) {
// if (!isSimpleFolder) {
// continue;
// }
// const rel = relativePath(this.project.path, path);
// const dir = CMAKE_CWD + '/' + rel;
// lines.push(`add_subdirectory(${JSON.stringify(dir)} ${JSON.stringify(objectName)})`);
// }
// }
return lines.join('\n');
}
const flags = (c_flags?: Array<string>, cpp_flags?: Array<string>, c_cpp_flags?: Array<string>): string => {
const map = (...from: (ReadonlyArray<string> | undefined)[]) => {
const args: string[] = [''].concat(...from.map(a => a ? a.slice() : [])).filter(e => !!e)
const arr = args || []
if (arr.length === 0) {
return ''
}
return arr.map(item => ` ${JSON.stringify(item)}`).join('\n')
};
const append = (str: string, varName: string) => {
if (str) {
content.push(`set(FLAGS_FOR_${varName}\n${str}\n)`)
}
return !!str
};
const content: string[] = []
content.push('')
content.push('##### flags from config json #####')
content.push('message("config flags for ${PROJECT_NAME}")')
const editCFlags = append(map(c_flags, c_cpp_flags), 'C')
const editCXXFlags = append(map(cpp_flags, c_cpp_flags), 'CXX')
if (editCFlags || editCXXFlags) {
content.push(`target_compile_options(\${PROJECT_NAME} PRIVATE`)
if (editCFlags) {
content.push(`\t$<$<COMPILE_LANGUAGE:C>:\${FLAGS_FOR_C}>`)
}
if (editCXXFlags) {
content.push(`\t$<$<COMPILE_LANGUAGE:CXX>:\${FLAGS_FOR_CXX}>`)
}
content.push(')')
}
return content.join('\n')
}
const linkSubProjects = (isRoot: boolean, dependencies?: Array<ProjectInfo>): string => {
if (!isRoot || !dependencies) {
return '';
}
interface LinkArguments {
options: Array<string>
objects: Array<string>
}
const linkArguments: LinkArguments = {
options: [
// Default flags
"-nostartfiles",
"-Wl,--gc-sections"
],
objects: []
}
dependencies.map(dependency => {
// Options(Link arguments and ld file)
if (dependency.config.ld_file) {
linkArguments.options.unshift('-T', `\${CMAKE_CURRENT_LIST_DIR}/kendryte_libraries/${dependency.config.name}/${dependency.config.ld_file}`)
}
if (dependency.config.link_flags) {
linkArguments.options = dependency.config.link_flags.concat(linkArguments.options)
}
// Objects(LinkArgumentPrefix PackageName LinkArgumentSuffix and SystemLibrary)
// Add "\"" string on arguments
const addQuot = (list: Array<string> = []): Array<string> => {
list.map((item, index) => {
list[index] = `"${item}"`
})
return list
}
dependency.config.linkArgumentPrefix = addQuot(dependency.config.linkArgumentPrefix)
dependency.config.linkArgumentSuffix = addQuot(dependency.config.linkArgumentSuffix)
dependency.config.systemLibrary = addQuot(dependency.config.systemLibrary)
// Add library name
linkArguments.objects.push(`## ${dependency.config.name}`)
// Add system library options first
linkArguments.objects = linkArguments.objects.concat(dependency.config.systemLibrary)
// if (!dependency.config.linkArgumentPrefix && !dependency.config.systemLibrary && !dependency.config.linkArgumentSuffix) {
// linkArguments.objects.push('No link component')
// return
// }
linkArguments.objects = linkArguments.objects.concat(dependency.config.linkArgumentPrefix)
linkArguments.objects = linkArguments.objects.concat(`"${dependency.config.name}"`)
linkArguments.objects = linkArguments.objects.concat(dependency.config.linkArgumentSuffix)
})
const p1 = linkArguments.options.map(line => {
return `"${line}"`
}).join('\n\t').trim()
const p2 = linkArguments.objects.map(line => {
return line
}).join('\n\t').trim()
let ret = '';
// Link Arugments
if (p1) {
ret += `target_link_options(\${PROJECT_NAME} PUBLIC\n\t${p1}\n)\n`;
}
// LinkArgumentPrefix PackageName LinkArgumentSuffix systemLibrary
if (p2) {
ret += `target_link_libraries(\${PROJECT_NAME} PUBLIC -Wl,--start-group\n\t${p2}\n-Wl,--end-group)\n`;
}
return ret;
}
const finishSection = (fileReader: FileList) =>{
return [
fileReader.afterProject,
"### include(fix9985)",
fileReader.fix9985,
].join('\n')
}
const flashable = (isRoot: boolean, type: string, fileReader: FileList) => {
if (isRoot && type !== 'library') {
return fileReader.flash
} else {
return ''
}
}

20
src/command/openocd.ts Normal file
View File

@ -0,0 +1,20 @@
import * as vscode from 'vscode'
import { OpenocdService } from '@service/openocd'
export const openocdStart = (openocdService: OpenocdService) => {
return vscode.commands.registerCommand('extension.openocd.start', async () => {
openocdService.start()
})
}
export const openocdStop = (openocdService: OpenocdService) => {
return vscode.commands.registerCommand('extension.openocd.stop', async () => {
openocdService.stop()
})
}
export const openocdRestart = (openocdService: OpenocdService) => {
return vscode.commands.registerCommand('extension.openocd.restart', () => {
openocdService.restart()
})
}

39
src/command/pickdevice.ts Normal file
View File

@ -0,0 +1,39 @@
import * as vscode from 'vscode'
import { Devices } from '@service/devices'
export const pickDevice = (devicesService: Devices): vscode.Disposable => {
return vscode.commands.registerCommand('extension.pickDevice', async () => {
return new Promise(async (resolve, reject) => {
const quickPick = vscode.window.createQuickPick()
let devices = await devicesService.getDiveceList()
devices = devices.filter(portInfo => {
return !!portInfo.productId
})
console.log(devices)
quickPick.items = devices.map((portInfo): vscode.QuickPickItem => {
return {
// label: portInfo.manufacturer ? `${portInfo.comName}: ${portInfo.manufacturer}` : portInfo.comName,
label: portInfo.comName,
description: portInfo.serialNumber || portInfo.productId,
detail: portInfo.pnpId,
picked: portInfo.comName === devicesService.device,
}
})
if (quickPick.items.length === 0) {
reject('No device found')
return
}
quickPick.show()
quickPick.onDidChangeSelection(async event => {
await devicesService.setDevice(event[0].label)
quickPick.dispose()
resolve(devicesService.device)
})
quickPick.onDidHide(event => {
if (!devicesService.device) {
vscode.window.showErrorMessage('Please select a device.')
}
})
})
})
}

View File

@ -0,0 +1,9 @@
import * as vscode from 'vscode'
import { initialization } from '../initialization'
export const reinstallPackages = (context: vscode.ExtensionContext): vscode.Disposable => {
return vscode.commands.registerCommand('extension.reinstallPackages', async () => {
await context.globalState.update('k210Packages', {})
initialization(context)
})
}

30
src/command/serialport.ts Normal file
View File

@ -0,0 +1,30 @@
import * as vscode from 'vscode'
import { Devices } from '@service/devices'
import { FrontendChannelLogger } from '@utils/index'
import { SerialPortService } from '@service/serialport'
export const openSerialPort = (deviceService: Devices, logger: FrontendChannelLogger, serialPort: SerialPortService): vscode.Disposable => {
return vscode.commands.registerCommand('extension.openSerialPort', async () => {
if (!deviceService.device) {
await vscode.commands.executeCommand('extension.pickDevice')
}
logger.show()
if (serialPort.status) {
logger.info(`===================== Stop serial port output ${(new Date()).toLocaleTimeString()} =====================`)
serialPort.setStatus(false)
} else {
serialPort.setStatus(true)
serialPort.on('data', data => {
logger.info(data)
})
serialPort.on('close', err => {
if (err && err.disconnected) {
serialPort.disposeSerialPort()
vscode.window.showInformationMessage(`${deviceService.device} disconnected.`)
deviceService.setDevice()
}
serialPort.removeAllListeners()
})
}
})
}

115
src/command/upload.ts Normal file
View File

@ -0,0 +1,115 @@
import * as vscode from 'vscode'
import { spawn } from 'child_process'
import { writeFileSync, readFileSync } from 'fs'
import * as JSZip from 'jszip'
import { Devices, SerialPortService } from '@service/index'
import { projectConfigParser, flashConfigParser, FlashList, BinaryFile } from '@common/index'
import { FrontendChannelLogger, systemFilter } from '@utils/index'
import { join } from 'path'
export const buildAndUpload = (context: vscode.ExtensionContext, deviceServices: Devices, uploadLogger: FrontendChannelLogger, serialPortService: SerialPortService): vscode.Disposable => {
return vscode.commands.registerCommand('extension.buildAndUpload', async () => {
let path: string
if (vscode.workspace.rootPath) {
path = `${vscode.workspace.rootPath}/build`
} else {
vscode.window.showErrorMessage('Please open a kendryte workspace')
return
}
const reader = await projectConfigParser(vscode.workspace.rootPath)
if (!reader) {
vscode.window.showErrorMessage('Please open a kendryte workspace')
return
}
await vscode.commands.executeCommand('extension.build')
// Generate flash-list.json file
const flashList: FlashList = {
version: '1.0.0',
files: []
}
const projectBin: BinaryFile = {
address: '0',
bin: `${reader.name}.bin`,
sha256Prefix: true
}
flashList.files.push(projectBin)
const extraSource: Array<string> = []
// Read flash-manager.json
const flashConfig = await flashConfigParser(`${vscode.workspace.rootPath}`)
if (flashConfig) {
flashConfig.downloadSections.map(section => {
const sectionConfig: BinaryFile = {
address: section.address.padEnd(10, '0'),
bin: section.filename,
sha256Prefix: false
}
flashList.files.push(sectionConfig)
extraSource.push(`${vscode.workspace.rootPath}/${section.filename}`)
})
}
// Write flash-list.json file
writeFileSync(`${path}/flash-list.json`, JSON.stringify(flashList))
const firmwarePath = `${path}/${reader.name}.bin`
const flashListPath = `${path}/flash-list.json`
// Package to .kfpkg
extraSource.push(flashListPath) // Push flash-list.json file
const zip = new JSZip()
// Add firmware
zip.file(`${reader.name}.bin`, readFileSync(firmwarePath))
// Add flash-list.json
zip.file('flash-list.json', readFileSync(flashListPath, 'utf-8'))
// Add extra source
extraSource.map(source => zip.file(source.replace(/(.*\/)*([^.]+)/i, '$2'), readFileSync(source)))
try {
const buffer = await zip.generateAsync({type: 'nodebuffer'})
writeFileSync(`${path}/${reader.name}.kfpkg`, buffer)
} catch(e) {
vscode.window.showErrorMessage('Generate .kfpkg file failed.')
return
}
const options = {
cwd: path,
env: {
Path: join(process.env.packagePath || '', 'python')
}
}
if (!deviceServices.device) {
// 如果未选择可用设备,会在此中断函数
await vscode.commands.executeCommand('extension.pickDevice')
}
uploadLogger.show()
const Unixargs = ['-b', '2000000', '-p', <string>deviceServices.device, `${reader.name}.kfpkg`]
const windowsArgs = [join(process.env.packagePath || '', 'kflash\\kflash.py'), '-b', '2000000', '-p', <string>deviceServices.device, `${reader.name}.kfpkg`]
const windowsExec = 'python'
// Stop serialport service when upload
await serialPortService.disconnectService()
const executable = systemFilter(windowsExec, join(process.env.packagePath || '', 'kflash/kflash'), join(process.env.packagePath || '', 'kflash/kflash'))
const args = systemFilter(windowsArgs, Unixargs, Unixargs)
const sdkProcess = spawn(executable, args, options)
sdkProcess.stdout.on('data', (data) => {
uploadLogger.info(data)
console.log(`stdout: ${data}`)
})
sdkProcess.stderr.on('data', (data) => {
uploadLogger.error(data)
console.log(`stderr: ${data}`)
})
sdkProcess.on('close', (code) => {
uploadLogger.info('Upload finished.')
deviceServices.setDevice(<string>deviceServices.device)
console.log(`子进程退出,退出码 ${code}`)
})
})
}

View File

@ -0,0 +1,3 @@
export const addDependency = async (packageName: string, version?: string): Promise<void> => {
}

View File

@ -0,0 +1 @@
export * from './install'

View File

@ -0,0 +1,37 @@
import * as vscode from 'vscode'
import { downloadPackage, jszipUnarchive, urlJoin} from '@utils/index'
import * as path from 'path'
export const installPackage = async (
packageName: string,
version: string,
workspacePath: string,
packageList: { [key: string]: any },
remoteHost: string,
localDependencies: { [key: string]: string }
): Promise<{ [key: string]: string }> => {
console.log(localDependencies)
console.log(`Install ${packageName}`)
try {
const fileName = `${packageName}_${version}.zip`
await downloadPackage(path.join(workspacePath, 'kendryte_libraries'), urlJoin(remoteHost, 'package', fileName), fileName)
await jszipUnarchive(path.join(workspacePath, 'kendryte_libraries', fileName), path.join(workspacePath, 'kendryte_libraries', packageName))
localDependencies[packageName] = version
const dependencies = packageList[packageName].versions[version].dependencies
for (let dependency of Object.keys(dependencies)) {
if (!localDependencies.hasOwnProperty(dependency)) {
try {
await installPackage(dependency, dependencies[dependency], workspacePath, packageList, remoteHost, localDependencies)
} catch (err) {
vscode.window.showErrorMessage(err)
}
} else {
console.log(`Skip install ${dependency}`)
}
}
return localDependencies
} catch (err) {
console.log(err)
return localDependencies
}
}

View File

@ -0,0 +1,12 @@
import { ProjectConfig } from '@command/makefileService/types'
import { FlashConfig } from '@common/index'
import { configReader } from '@utils/index'
export const flashConfigParser = async (path: string): Promise<FlashConfig | undefined> => {
const reader = configReader<FlashConfig>(`${path}/config/flash-manager.json`)
if (!reader) {
return
}
return reader
}

27
src/common/flash/types.ts Normal file
View File

@ -0,0 +1,27 @@
export interface FlashConfig {
baseAddress: string
totalSize: number
endAddress: string
downloadSections: {
id: string
filesize: number
name: string
address: string
autoAddress: boolean
filename: string
addressEnd: string
swapBytes: boolean
}[]
[key:string]: any
}
export interface BinaryFile {
address: string
bin: string
sha256Prefix: boolean
}
export interface FlashList {
version: string
files: Array<BinaryFile>
}

7
src/common/index.ts Normal file
View File

@ -0,0 +1,7 @@
export * from './project-config-parser'
export * from './flash/flashconfigparser'
export * from './flash/types'
export * from './react-panel'
export * from './local-dependencies'
export * from './add-dependency'
export * from './dependency'

View File

@ -0,0 +1,30 @@
import * as vscode from 'vscode'
import * as path from 'path'
import { statSync } from 'fs'
import { projectConfigParser } from '@common/project-config-parser'
import { ProjectConfig } from '@command/makefileService/types'
import { readdirPromisify } from '@utils/index'
export const localDependenciesReader = async (): Promise<ProjectConfig["dependencies"]> => {
return new Promise(async (resolve, reject) => {
if (!vscode.workspace.rootPath) {
return
}
const localDependencies: ProjectConfig["dependencies"] = {}
const dependenciesPath = path.join(vscode.workspace.rootPath, 'kendryte_libraries')
readdirPromisify(dependenciesPath)
.then(async dependenciesList => {
await Promise.all(dependenciesList.map(async dependency => {
const dependencyPath = path.join(dependenciesPath, dependency)
if (!statSync(dependencyPath).isDirectory()) return
const config = await projectConfigParser(dependencyPath)
if (!config) return
localDependencies[config.name] = config.version
}))
resolve(localDependencies)
})
.catch(err => {
resolve(localDependencies)
})
})
}

View File

@ -0,0 +1,70 @@
import { window } from 'vscode'
import * as fg from 'fast-glob'
import { ProjectConfig } from '@command/makefileService/types'
import { configReader } from '@utils/index'
import { join } from 'path'
export const projectConfigParser = async (path: string): Promise<ProjectConfig | undefined> => {
const reader = configReader<ProjectConfig>(`${path}/kendryte-package.json`)
if (!reader) {
window.showErrorMessage(`Cannot find kendryte-package.json on ${path}. Please check it and reinstall dependencies.`)
return
}
const originalDependency: ProjectConfig["dependencies"] = reader.dependencies || {}
const dependencyList = Object.keys(originalDependency) // 原始包名 list ,格式与目录中不同,需要处理
const dependency: ProjectConfig["dependencies"] = {}
const includes = reader.include || []
const isLib = /\/kendryte_libraries\//.test(path)
const includeList: Array<string> = []
await Promise.all(dependencyList.map(async dependencyItem => {
// 包名格式化
const dependencyValue = originalDependency[dependencyItem]
const name = dependencyItem.replace(/\//g, '_')
dependency[name] = dependencyValue
// 以下为 include 检测
dependencyItem = (!isLib ? 'kendryte_libraries/' : '../') + name // kendryte_libraries/kendryte_xxx-xxx || ../kendryte_xxx-xxx
const dependencyPath = `${path}/${dependencyItem}`
// Include 包含两部分1. 依赖中 include 目录 2. 手动配置的 include 3. 依赖中手动配置的 include 4. 自身 include 目录
// 依赖 include 检测
// try {
// const list = await fg('**/include', {
// cwd: dependencyPath,
// onlyDirectories: true
// })
// list.map((item, index) => {
// list[index] = `${dependencyItem}/${item}`
// })
// includeList.push.apply(includeList, list)
// } catch (err) {
// window.showErrorMessage(err)
// throw (err)
// }
// 添加依赖中手动定义的 include
const depReader = configReader<ProjectConfig>(join(dependencyPath, 'kendryte-package.json'))
if (depReader && depReader.include) {
depReader.include.map(include => includeList.push(join(dependencyItem, include).replace(/\\/g, '/')))
}
}))
// 手动配置 include 检测(不包含包中配置的 include
includes.map(include => includeList.push(include))
// 覆写 source 参数 /^a.*\.c$/
const originalSource = reader.source
const sourceArr: Array<string> = []
await Promise.all(originalSource.map(async item => {
const list = await fg(item, {
cwd: path,
onlyFiles: true
})
sourceArr.push.apply(sourceArr, list)
}))
reader.name = reader.name.replace(/\//, '_')
reader.source = sourceArr
reader.dependencies = dependency // 覆写格式化后过的依赖列表
reader.includeFolders = includeList
return reader
}

147
src/common/react-panel.ts Normal file
View File

@ -0,0 +1,147 @@
import * as vscode from 'vscode'
import * as path from 'path'
import * as fs from 'fs'
import { messageHandler } from '@common/webviewResponse'
/**
* Manages react webview panels
*/
export class ReactPanel {
/**
* Track the currently panel. Only allow a single panel to exist at a time.
*/
public static currentPanel: ReactPanel | undefined
private static readonly viewType = 'react'
private readonly _panel: vscode.WebviewPanel
private readonly _extensionPath: string
private _disposables: vscode.Disposable[] = []
public static createOrShow(extensionPath: string, subscriptions: vscode.Disposable[]) {
const column = vscode.window.activeTextEditor ? vscode.window.activeTextEditor.viewColumn : undefined
// If we already have a panel, show it.
// Otherwise, create a new panel.
if (ReactPanel.currentPanel) {
ReactPanel.currentPanel._panel.reveal(column)
} else {
ReactPanel.currentPanel = new ReactPanel(extensionPath, subscriptions, column || vscode.ViewColumn.One)
}
}
private constructor(extensionPath: string, subscriptions: vscode.Disposable[], column: vscode.ViewColumn) {
this._extensionPath = extensionPath
// Create and show a new webview panel
this._panel = vscode.window.createWebviewPanel(ReactPanel.viewType, "Kendryte", column, {
// Enable javascript in the webview
enableScripts: true,
// And restric the webview to only loading content from our extension's `media` directory.
localResourceRoots: [
vscode.Uri.file(path.join(this._extensionPath, 'build/react-views'))
]
})
// Set the webview's initial html content
this._panel.webview.html = this._getHtmlForWebview()
this._panel.iconPath = vscode.Uri.file(path.join(this._extensionPath, 'resources/kendryte.svg'))
// Listen for when the panel is disposed
// This happens when the user closes the panel or when the panel is closed programatically
this._panel.onDidDispose(() => this.dispose(), null, this._disposables)
// Handle messages from the webview
this._panel.webview.onDidReceiveMessage(async message => {
console.log(message)
const msg = await messageHandler(message, extensionPath)
console.log(msg)
this._panel.webview.postMessage({
...msg,
symbol: message.symbol
})
}, undefined, this._disposables)
}
public doRefactor() {
// Send a message to the webview webview.
// You can send any JSON serializable data.
this._panel.webview.postMessage({ command: 'refactor' })
}
public dispose() {
ReactPanel.currentPanel = undefined
// Clean up our resources
this._panel.dispose()
while (this._disposables.length) {
const x = this._disposables.pop()
if (x) {
x.dispose()
}
}
}
private _getHtmlForWebview() {
const manifest = JSON.parse(fs.readFileSync(path.join(this._extensionPath, 'build/react-views', 'asset-manifest.json'), 'utf-8'))
const mainStyle = manifest.files['main.css']
const stylePathOnDisk = vscode.Uri.file(path.join(this._extensionPath, 'build/react-views', mainStyle))
const styleUri = stylePathOnDisk.with({ scheme: 'vscode-resource' })
// Use a nonce to whitelist which scripts can be run
const nonce = getNonce()
const scripts = this._getScripts()
const scriptTags = () => {
return scripts.map(script => {
return `<script nonce="${nonce}" src="${script}"></script>`
})
}
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no">
<meta name="theme-color" content="#000000">
<title>Kendryte</title>
<link rel="stylesheet" type="text/css" href="${styleUri}">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src vscode-resource: https:; script-src https: 'nonce-${nonce}'; style-src vscode-resource: 'unsafe-inline' https: data:; connect-src https:">
<base href="${vscode.Uri.file(path.join(this._extensionPath, 'build/react-views')).with({ scheme: 'vscode-resource' })}/">
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
${scriptTags()}
</body>
</html>`
}
private _getScripts(): Array<vscode.Uri> {
const manifest = JSON.parse(fs.readFileSync(path.join(this._extensionPath, 'build/react-views', 'asset-manifest.json'), 'utf-8'))
let entryFiles: Array<string> = manifest.entrypoints
entryFiles = entryFiles.filter((file: string) => {
return !/\.css$/.test(file)
})
return entryFiles.map((file: string) => {
const scriptPathOnDisk = vscode.Uri.file(path.join(this._extensionPath, 'build/react-views', file))
const scriptUri = scriptPathOnDisk.with({ scheme: 'vscode-resource' })
return scriptUri
})
}
}
function getNonce() {
let text = ""
const possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
for (let i = 0; i < 32; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length))
}
return text
}

View File

@ -0,0 +1,41 @@
import * as vscode from 'vscode'
import { downloadPackage, urlJoin, jszipUnarchive, systemFilter } from '@utils/index'
import { readFileSync } from 'fs'
import { join } from 'path'
export const installExample = (exampleName: string, extensionPath: string): Promise<void> => {
return new Promise((resolve, reject) => {
vscode.window.showOpenDialog({
canSelectFiles: false,
canSelectFolders: true,
canSelectMany: false
})
.then(uri => {
if (!uri) {
reject()
return
}
const path = systemFilter(uri[0].path.replace(/^\//, ''), uri[0].path, uri[0].path)
const host = JSON.parse(readFileSync(join(extensionPath, 'config.json'), 'utf-8')).host
const exampleUrl = urlJoin(host, 'example', `${exampleName}_0.1.0.zip`)
console.log(exampleUrl)
downloadPackage(path, exampleUrl, `${exampleName}.zip`)
.then(() => {
jszipUnarchive(join(path, `${exampleName}.zip`), join(path, exampleName))
.then(async () => {
if (vscode.workspace.rootPath) {
await vscode.commands.executeCommand('vscode.openFolder', vscode.Uri.file(join(path, exampleName)), true)
} else {
await vscode.commands.executeCommand('vscode.openFolder', vscode.Uri.file(join(path, exampleName)), false)
}
resolve()
})
.catch(err => reject(`Extract ${exampleName} failed`))
})
.catch(err => {
console.log(err)
reject(`Download ${exampleName} failed`)
})
})
})
}

View File

@ -0,0 +1,52 @@
import * as vscode from 'vscode'
import { localDependenciesReader } from '@common/local-dependencies'
import { installExample } from '@common/webviewResponse/example'
import { createNewProject } from '@common/webviewResponse/newProject'
export const messageHandler = async (msg: any, extensionPath: string) => {
switch(msg.type) {
case 'check':
const dependencies = await localDependenciesReader()
const response = {
type: "response",
data: {
dependencies: Object.keys(dependencies || {})
}
}
return response
case 'package':
try {
await vscode.commands.executeCommand('extension.addDependency', msg.name)
} catch(err) {
vscode.window.showErrorMessage(err)
return ({
type: 'error',
error: 'Something wrong'
})
}
return({})
case 'example':
try {
await installExample(msg.name, extensionPath)
} catch(err) {
vscode.window.showErrorMessage(err)
return ({
type: 'error',
error: 'Download example failed.'
})
}
return({})
case 'create':
try {
await createNewProject()
} catch(err) {
vscode.window.showErrorMessage(err)
return ({
type: 'error',
error: 'Create new project failed.'
})
}
return({})
default:
}
}

View File

@ -0,0 +1,58 @@
import * as vscode from 'vscode'
import * as fs from 'fs'
import { readdirPromisify } from '@utils/index'
import { join } from 'path'
const copyDir = (path: string, targetPath: string) => {
return new Promise((resolve, reject) => {
try {
fs.mkdirSync(targetPath)
} catch(e) {
console.log(e)
}
readdirPromisify(path)
.then(items => {
items.map(item => {
const itemPath = join(path, item)
if (fs.statSync(itemPath).isDirectory()) {
copyDir(join(path, item), join(targetPath, item))
} else {
const buffer = fs.readFileSync(join(path, item))
try {
fs.writeFileSync(join(targetPath, item), buffer)
} catch (err) {
reject(`Create file ${item} failed`)
console.log(err)
}
}
})
resolve()
})
.catch(err => {
console.log(err)
reject('No such directory.')
})
})
}
export const createNewProject = () => {
return new Promise((resolve, reject) => {
vscode.window.showOpenDialog({
canSelectFiles: false,
canSelectFolders: true,
canSelectMany: false
})
.then(uri => {
if (!uri || !process.env.packagePath) {
reject()
return
}
copyDir(join(process.env.packagePath, 'hello-world-project'), join(uri[0].path, 'hello-world'))
.then(async () => {
await vscode.commands.executeCommand('vscode.openFolder', vscode.Uri.file(join(uri[0].path, 'hello-world')), true)
resolve()
})
.catch(err => reject(err))
})
})
}

View File

@ -0,0 +1,5 @@
import { IGDBStackFrame } from './stackFrame'
export interface IGDBStack {
frame: IGDBStackFrame
}

View File

@ -0,0 +1,9 @@
export interface IGDBStackFrame {
level: string // number
addr: string // hex
func: string
file: string
fullname: string
line?: string // number
from?: string // number ???
}

View File

@ -0,0 +1,9 @@
import { IGDBThreadFrame } from './threadFrame'
export interface IGDBThread {
id: string
'target-id': string
name?: string
frame: IGDBThreadFrame
state: string
}

View File

@ -0,0 +1,9 @@
export interface IGDBThreadFrame {
level: string // number
addr: string // hex
func: string
args: string[]
file: string
fullname: string
line: string // number
}

View File

@ -0,0 +1,5 @@
export interface IGDBVariable {
name: string
type: string
value: string
}

View File

@ -0,0 +1,628 @@
import { posix } from 'path'
import { DebugSession, Handles, InitializedEvent, Scope, Source, StackFrame, Thread } from 'vscode-debugadapter'
import { DebugProtocol } from 'vscode-debugprotocol'
import { IMyLogger } from '@utils/baseLogger'
import { objectPath } from '../common/library/objectPath'
import { errorMessage, errorStack } from '../common/library/strings'
import { isCommandIssueWhenRunning } from '../common/mi2/mi2AutomaticResponder'
import { createStopEvent, StopReason } from '../common/mi2/pause'
import { BreakpointType, MyBreakpointFunc, MyBreakpointLine } from '../common/mi2/types'
import { toProtocolBreakpoint } from '../common/mi2/types.convert'
import { BackendLogger } from './lib/backendLogger'
import { IDebugConsole, wrapDebugConsole } from './lib/duplexDebugConsole'
import { ErrorCode, ErrorMi2, handleMethodPromise } from './lib/handleMethodPromise'
import { expandValue } from './session/gdb_expansion'
import { DebuggingSession } from './session/session'
import { AttachRequestArguments, LaunchRequestArguments, ValuesFormattingMode, VariableObject } from './type'
const resolve = posix.resolve
const relative = posix.relative
class ExtendedVariable {
constructor(public name: VariableId, public options: any) {
}
}
type VariableId = number | string | VariableObject | ExtendedVariable
enum ErrorCodeValue {
Unknown = 1,
Restart,
Initialize,
Evaluate,
Attach,
Launch,
Disconnect,
SetVariable,
Breakpoints,
Threads,
StackTrace,
init,
Scopes,
VariableNumber,
VariableString,
ExpandVariable,
VariableObject,
VariableExtend,
Continue,
Pause,
StepIn,
StepOut,
StepNext,
}
const STACK_HANDLES_START = 1000
const VAR_HANDLES_START = 512 * 256 + 1000
export class KendryteDebugger extends DebugSession {
protected variableHandles = new Handles<VariableId>(VAR_HANDLES_START)
protected variableHandlesReverse: { [id: string]: number } = {}
protected useVarObjects!: boolean
protected debugInstance!: DebuggingSession
protected readonly debugLogger: IMyLogger
protected readonly vscodeProtocolLogger: IMyLogger
private readonly debugConsole: IDebugConsole
private initComplete: boolean = false
private autoContinue: boolean = true
private firstThreadRequest: boolean = true
public constructor(debuggerLinesStartAt1: boolean, isServer: boolean = false) {
super(debuggerLinesStartAt1, isServer)
this.vscodeProtocolLogger = new BackendLogger('protocol', this)
this.debugLogger = new BackendLogger('gdb', this)
this.debugConsole = wrapDebugConsole(this, this.vscodeProtocolLogger)
process.on('unhandledRejection', (reason, p) => {
p.catch((e) => {
if (e instanceof ErrorMi2) {
this.debugLogger.error('Unhandled Mi2 Rejection: ' + (e.node.token ? 'token=' + e.node.token : 'result=' + e.node.rawLine))
this.debugLogger.error(errorStack(e))
} else {
this.debugLogger.error('Unhandled Rejection: ' + errorStack(e))
}
this.debugConsole.errorUser('[kendryte debug] Unhandled Rejection: ' + errorMessage(e))
})
})
process.on('uncaughtException', (err) => {
console.error(err)
this.debugLogger.error('uncaughtException: ' + errorStack(err))
this.debugConsole.errorUser('[kendryte debug] Fatal error during debugging session. Catched unhandled exception.\n' + errorStack(err))
setTimeout(() => {
process.exit(1)
}, 2000)
})
}
private fireEvent(ev: DebugProtocol.Event) {
if (this.autoContinue && !this.initComplete && (ev.event === 'stopped' || ev.event === 'continued')) {
this.vscodeProtocolLogger.info('initialize not complete, event muted:', JSON.stringify(ev))
return
}
this.vscodeProtocolLogger.info('fireEvent: [%s]%s', ev.event, JSON.stringify(ev.body))
this.sendEvent(ev)
}
private resetStatus() {
delete this.debugInstance
this.initComplete = false
this.autoContinue = true
}
private async attachOrLaunch(args: AttachRequestArguments | LaunchRequestArguments, load: boolean) {
if (this.debugInstance) {
await this.debugInstance.terminate()
}
const logger = new BackendLogger(args.id ? 'gdb-' + args.id : 'gdb-main', this)
const debugConsole = wrapDebugConsole(this, logger)
this.debugInstance = new DebuggingSession(args, logger, debugConsole)
this.debugInstance.onEvent((ev) => this.fireEvent(ev))
await this.debugInstance.connect(load)
this.setValuesFormattingMode(args.valuesFormatting)
this.debugInstance.disconnected.then((self) => {
if (self === this.debugInstance) {
this.resetStatus()
}
})
this.sendEvent(new InitializedEvent())
this.initComplete = true
}
protected setValuesFormattingMode(mode: ValuesFormattingMode) {
switch (mode) {
case 'disabled':
this.useVarObjects = true
// this.debugInstance.prettyPrint = false
break
case 'prettyPrinters':
this.useVarObjects = true
// this.debugInstance.prettyPrint = true
break
case 'parseText':
default:
this.useVarObjects = false
// this.debugInstance.prettyPrint = false
}
}
// Supports 256 threads.
protected threadAndLevelToFrameId(threadId: number, level: number) {
return level << 8 | threadId
}
protected frameIdToThreadAndLevel(frameId: number) {
return [frameId & 0xff, frameId >> 8]
}
private _createVariable(arg: VariableId, options?: any) {
if (options) {
return this.variableHandles.create(new ExtendedVariable(arg, options))
} else {
return this.variableHandles.create(arg)
}
}
private _findOrCreateVariable(varObj: VariableObject): number {
let id: number
if (this.variableHandlesReverse.hasOwnProperty(varObj.name)) {
id = this.variableHandlesReverse[varObj.name]
} else {
id = this._createVariable(varObj)
this.variableHandlesReverse[varObj.name] = id
}
return varObj.isCompound() ? id : 0
}
@handleMethodPromise(ErrorCodeValue.VariableNumber)
private async variableNumber(response: DebugProtocol.VariablesResponse, id: number): Promise<void> {
const variables: DebugProtocol.Variable[] = []
const [threadId, level] = this.frameIdToThreadAndLevel(id)
const stack = await this.debugInstance.getStackVariables(threadId, level)
for (const variable of stack) {
if (this.useVarObjects) {
try {
const varObjName = `var_${id}_${variable.name}`
let varObj: VariableObject
try {
const changes = await this.debugInstance.varUpdate(varObjName)
const changelist = changes.result('changelist')
changelist.forEach((change: any) => {
const name = objectPath(change, 'name')
const vId = this.variableHandlesReverse[name]
const v = this.variableHandles.get(vId) as any
v.applyChanges(change)
})
const varId = this.variableHandlesReverse[varObjName]
varObj = this.variableHandles.get(varId) as any
} catch (err) {
if (err.message.includes('Variable object not found')) {
varObj = await this.debugInstance.varCreate(variable.name, varObjName)
const varId = this._findOrCreateVariable(varObj)
varObj.exp = variable.name
varObj.id = varId
} else {
return Promise.reject(err)
}
}
variables.push(varObj.toProtocolVariable())
} catch (err) {
variables.push({
name: variable.name,
value: `<${err}>`,
variablesReference: 0,
})
}
} else {
if (variable.valueStr !== undefined) {
let expanded = expandValue(this._createVariable.bind(this), `{${variable.name}=${variable.valueStr})`, '', variable.raw)
if (expanded) {
if (typeof expanded[0] == 'string') {
expanded = [
{
name: '<value>',
value: prettyStringArray(expanded),
variablesReference: 0,
},
]
}
variables.push(expanded[0])
}
} else {
variables.push({
name: variable.name,
type: variable.type,
value: '<unknown>',
variablesReference: this._createVariable(variable.name),
})
}
}
}
response.body = { variables }
}
@handleMethodPromise(ErrorCodeValue.VariableString)
private async variableString(response: DebugProtocol.VariablesResponse, id: string) {
// Variable members
// TODO: this evals on an (effectively) unknown thread for multithreaded programs.
const variable = await this.debugInstance.evalExpression(JSON.stringify(id), 0, 0)
let expanded = expandValue(this._createVariable.bind(this), variable.result('value'), id, variable)
if (!expanded) {
throw new ErrorCode(ErrorCodeValue.ExpandVariable, `Could not expand variable`)
} else {
if (typeof expanded[0] == 'string') {
expanded = [
{
name: '<value>',
value: prettyStringArray(expanded),
variablesReference: 0,
},
]
}
response.body = { variables: expanded }
}
}
@handleMethodPromise(ErrorCodeValue.VariableObject)
private async variableObject(response: DebugProtocol.VariablesResponse, id: VariableObject) {
// Variable members
const children: VariableObject[] = await this.debugInstance.varListChildren(id.name)
const vars = children.map(child => {
child.id = this._findOrCreateVariable(child)
return child.toProtocolVariable()
})
response.body = { variables: vars }
}
@handleMethodPromise(ErrorCodeValue.VariableExtend)
private async variableExtended(response: DebugProtocol.VariablesResponse, varReq: ExtendedVariable) {
response.body = { variables: [] }
if (varReq.options.arg) {
let argsPart = true
let arrIndex = 0
const addOne = async () => {
// TODO: this evals on an (effectively) unknown thread for multithreaded programs.
const variable = await this.debugInstance.evalExpression(JSON.stringify(`${varReq.name}+${arrIndex})`), 0, 0)
const expanded = expandValue(this._createVariable.bind(this), variable.result('value'), '' + varReq.name, variable)
if (!expanded) {
throw new ErrorCode(ErrorCodeValue.ExpandVariable, `Could not expand variable`)
}
try {
if (typeof expanded == 'string') {
if (expanded == '<nullptr>') {
if (argsPart) {
argsPart = false
} else {
return
}
} else if (expanded[0] != '"') {
response.body.variables.push({
name: '[err]',
value: expanded,
variablesReference: 0,
})
return
}
response.body.variables.push({
name: `[${(arrIndex++)}]`,
value: expanded,
variablesReference: 0,
})
await addOne()
} else {
response.body.variables.push({
name: '[err]',
value: expanded,
variablesReference: 0,
})
return
}
} catch (e) {
throw new ErrorCode(ErrorCodeValue.ExpandVariable, `Could not expand variable: ${e}`)
}
}
await addOne()
} else {
throw new ErrorCode(13, `Unimplemented variable request options: ${JSON.stringify(varReq.options)}`)
}
}
@handleMethodPromise(ErrorCodeValue.Initialize)
protected initializeRequest(response: DebugProtocol.InitializeResponse, args: DebugProtocol.InitializeRequestArguments): void {
this.vscodeProtocolLogger.info('initializeRequest: ')
if (response.body) {
response.body.supportsConfigurationDoneRequest = true
response.body.supportsConditionalBreakpoints = true
response.body.supportsFunctionBreakpoints = true
response.body.supportsEvaluateForHovers = true
response.body.supportsSetVariable = true
response.body.supportsRestartRequest = true
response.body.supportsLogPoints = true
}
}
@handleMethodPromise(ErrorCodeValue.Disconnect)
disconnectRequest(response: DebugProtocol.DisconnectResponse, args: DebugProtocol.DisconnectArguments) {
return this.debugInstance.terminate()
}
@handleMethodPromise(ErrorCodeValue.Launch)
protected launchRequest(response: DebugProtocol.LaunchResponse, args: LaunchRequestArguments) {
return this.attachOrLaunch(args, true)
}
@handleMethodPromise(ErrorCodeValue.Attach)
protected async attachRequest(response: DebugProtocol.AttachResponse, args: AttachRequestArguments) {
return this.attachOrLaunch(args, false)
}
@handleMethodPromise(ErrorCodeValue.Restart)
async restartRequest(response: DebugProtocol.RestartResponse, args: DebugProtocol.RestartArguments) {
return this.debugInstance.reload()
}
@handleMethodPromise(ErrorCodeValue.Breakpoints)
async setBreakPointsRequest(response: DebugProtocol.SetBreakpointsResponse, args: DebugProtocol.SetBreakpointsArguments) {
await this.debugInstance.connected
const myBreaks: MyBreakpointLine[] = args.breakpoints ? args.breakpoints.map((bk) => {
return <MyBreakpointLine>{
type: BreakpointType.Line,
file: args.source.path,
line: bk.line,
condition: bk.condition,
logMessage: bk.logMessage,
}
}) : []
const resultBreaks = await this.debugInstance.updateBreakPoints(args.source.path || '', myBreaks)
if (!response.body) {
response.body = { breakpoints: [] }
}
if (!response.body.breakpoints) {
response.body.breakpoints = []
}
for (const newBreak of resultBreaks) {
response.body.breakpoints.push(toProtocolBreakpoint(newBreak))
}
}
@handleMethodPromise(ErrorCodeValue.Breakpoints)
async setFunctionBreakPointsRequest(response: DebugProtocol.SetFunctionBreakpointsResponse, args: DebugProtocol.SetFunctionBreakpointsArguments) {
await this.debugInstance.connected
const myBreaks: MyBreakpointFunc[] = args.breakpoints.map((bk) => {
return <MyBreakpointFunc>{
type: BreakpointType.Function,
name: bk.name,
condition: bk.condition,
}
})
const resultBreaks = await this.debugInstance.updateBreakPoints('', myBreaks)
if (!response.body) {
response.body = { breakpoints: [] }
}
if (!response.body.breakpoints) {
response.body.breakpoints = []
}
for (const newBreak of resultBreaks) {
response.body.breakpoints.push(toProtocolBreakpoint(newBreak))
}
}
@handleMethodPromise(ErrorCodeValue.init)
protected configurationDoneRequest(response: DebugProtocol.ConfigurationDoneResponse, args: DebugProtocol.ConfigurationDoneArguments): void {
this.debugConsole.logUser('Configuration done!')
setImmediate(() => {
if (this.autoContinue && !this.debugInstance.isRunning) {
this.debugInstance.continue().finally(() => {
this.debugLogger.writeln('')
})
} else if (!this.autoContinue && this.debugInstance.isRunning) {
this.debugInstance.interrupt().finally(() => {
this.debugLogger.writeln('')
})
}
})
}
@handleMethodPromise(ErrorCodeValue.Continue)
continueRequest(response: DebugProtocol.ContinueResponse, args: DebugProtocol.ContinueArguments) {
console.log('get continue')
return this.debugInstance.continue()
}
@handleMethodPromise(ErrorCodeValue.StepNext)
protected nextRequest(response: DebugProtocol.NextResponse, args: DebugProtocol.NextArguments) {
console.log('get next')
return this.debugInstance.next()
}
@handleMethodPromise(ErrorCodeValue.StepIn)
stepInRequest(response: DebugProtocol.NextResponse, args: DebugProtocol.NextArguments) {
return this.debugInstance.step()
}
@handleMethodPromise(ErrorCodeValue.StepOut)
stepOutRequest(response: DebugProtocol.NextResponse, args: DebugProtocol.NextArguments) {
return this.debugInstance.stepOut()
}
@handleMethodPromise(ErrorCodeValue.Pause)
async pauseRequest(response: DebugProtocol.PauseResponse, args: DebugProtocol.PauseArguments) {
await this.debugInstance.interrupt()
setTimeout(() => {
this.fireEvent(createStopEvent(StopReason.Pausing, undefined, 'pause button clicked'))
}, 500)
}
@handleMethodPromise(ErrorCodeValue.Threads)
async threadsRequest(response: DebugProtocol.ThreadsResponse) {
if (!this.debugInstance) {
return
}
const threads = await this.debugInstance.getThreads(this.firstThreadRequest).catch((e) => {
if (isCommandIssueWhenRunning(e)) {
return []
} else {
throw e
}
})
this.firstThreadRequest = false
response.body = {
threads: [],
}
for (const thread of threads) {
let threadName = thread.name
// TODO: Thread names are undefined on LLDB
if (threadName === undefined) {
threadName = thread.targetId
}
if (threadName === undefined) {
threadName = '<unnamed>'
}
response.body.threads.push(new Thread(thread.id, thread.id + ':' + threadName))
}
}
@handleMethodPromise(ErrorCodeValue.StackTrace)
protected async stackTraceRequest(response: DebugProtocol.StackTraceResponse, args: DebugProtocol.StackTraceArguments) {
const stack = await this.debugInstance.getStack(args.levels || 0, args.threadId)
const ret: StackFrame[] = []
stack.forEach(element => {
let source = undefined
let file = element.file
if (file) {
if (process.platform === 'win32') {
if (file.startsWith('\\cygdrive\\') || file.startsWith('/cygdrive/')) {
file = file[10] + ':' + file.substr(11) // replaces /cygdrive/c/foo/bar.txt with c:/foo/bar.txt
}
}
source = new Source(element.fileName, file)
}
ret.push(new StackFrame(
this.threadAndLevelToFrameId(args.threadId, element.level),
element.function + '@' + element.address,
source,
element.line,
0,
))
})
response.body = {
stackFrames: ret,
}
}
/*
@handleMethodPromise(4, 'Could not step back: %s - Try running \'target record-full\' before stepping back')
protected stepBackRequest(response: DebugProtocol.StepBackResponse, args: DebugProtocol.StepBackArguments): void {
return this.debugInstance.step()
}
*/
@handleMethodPromise(ErrorCodeValue.Scopes)
protected scopesRequest(response: DebugProtocol.ScopesResponse, args: DebugProtocol.ScopesArguments) {
const scopes: Scope[] = []
scopes.push(new Scope('Local', STACK_HANDLES_START + (parseInt(args.frameId as any) || 0), false))
response.body = {
scopes: scopes,
}
}
protected variablesRequest(response: DebugProtocol.VariablesResponse, args: DebugProtocol.VariablesArguments): Promise<void> | undefined {
let id: VariableId
if (args.variablesReference < VAR_HANDLES_START) {
id = args.variablesReference - STACK_HANDLES_START
} else {
id = this.variableHandles.get(args.variablesReference)
}
if (typeof id == 'number') {
return this.variableNumber(response, id)
} else if (typeof id == 'string') {
return this.variableString(response, id)
} else if (id && id instanceof VariableObject) {
return this.variableObject(response, id)
} else if (id && id instanceof ExtendedVariable) {
return this.variableExtended(response, id)
// } else if (typeof id === 'object') {
// response.body = {
// variables: id as any,
// }
// this.sendResponse(response)
} else {
response.body = { variables: [] }
this.sendResponse(response)
}
}
@handleMethodPromise(ErrorCodeValue.SetVariable)
async setVariableRequest(response: DebugProtocol.SetVariableResponse, args: DebugProtocol.SetVariableArguments): Promise<void> {
if (this.useVarObjects) {
let name = args.name
if (args.variablesReference >= VAR_HANDLES_START) {
const parent = this.variableHandles.get(args.variablesReference) as VariableObject
name = `${parent.name}.${name}`
}
const newValue = await this.debugInstance.varAssign(name, args.value)
response.body = { value: newValue }
} else {
const value = await this.debugInstance.changeVariable(args.name, args.value)
response.body = { value }
}
}
@handleMethodPromise(ErrorCodeValue.Evaluate)
async evaluateRequest(response: DebugProtocol.EvaluateResponse, args: DebugProtocol.EvaluateArguments) {
const [threadId, level] = this.frameIdToThreadAndLevel(args.frameId || 0)
if (args.context == 'watch' || args.context == 'hover') {
const res = await this.debugInstance.evalExpression(args.expression, threadId, level)
response.body = {
variablesReference: 0,
result: res.result('value'),
}
} else {
const output = await this.debugInstance.sendUserInput(args.expression, threadId, level)
if (typeof output == 'undefined') {
response.body = {
result: '',
variablesReference: 0,
}
} else {
response.body = {
result: JSON.stringify(output),
variablesReference: 0,
}
}
}
}
}
function prettyStringArray(strings: any) {
if (typeof strings == 'object') {
if (strings.length !== undefined) {
return strings.join(', ')
} else {
return JSON.stringify(strings)
}
} else {
return strings
}
}

View File

@ -0,0 +1,42 @@
import { DebugSession, Event } from 'vscode-debugadapter'
import { LogLevel, NodeLoggerCommon } from '@utils/baseLogger'
import { ILogEventBody } from '@debug/common/eventProtocol'
export class CustomEvent<T = any> extends Event {
constructor(type: string, event: T) {
super('custom', {
type,
event,
})
}
}
export class BackendLogger extends NodeLoggerCommon {
constructor(
tag: string,
private readonly session: DebugSession,
) {
super(tag)
}
public clear(): void {
this.session.sendEvent(
new CustomEvent<void>('clear-log', undefined),
)
}
public printLine(tag: string, level: LogLevel, message: string) {
if (message === '') {
this.session.sendEvent(
new CustomEvent<any>('nl', {}),
)
} else {
this.session.sendEvent(
new CustomEvent<ILogEventBody>('log', {
level: level,
message: `${tag}: ${message.replace(/^/g, ' ').trim()}`,
}),
)
}
}
}

View File

@ -0,0 +1,26 @@
import { DebugSession, OutputEvent } from 'vscode-debugadapter'
import { IMyLogger } from '@utils/baseLogger'
export interface IDebugConsole {
log(message: string): void
error(message: string): void
logUser(message: string): void
errorUser(message: string): void
}
export function wrapDebugConsole(session: DebugSession, logger: IMyLogger): IDebugConsole {
return {
logUser(message: string) {
this.log(message + '\n')
},
errorUser(message: string) {
this.error(message + '\n')
},
log(message: string) {
session.sendEvent(new OutputEvent(message, 'stdout'))
},
error(message: string) {
session.sendEvent(new OutputEvent(message, 'stderr'))
},
}
}

Some files were not shown because too many files have changed in this diff Show More