refactor: rewrite as yarn workspace, add cli as test tool (#98)

This commit is contained in:
Lucas Fernandes Nogueira
2021-04-26 10:14:59 -03:00
committed by GitHub
parent 57b18c4c1a
commit b874256141
42 changed files with 3209 additions and 17764 deletions

View File

@@ -3,19 +3,23 @@
"pkgManagers": {
"javascript": {
"version": true,
"publish": true
"build": false,
"preversion": "yarn pkg",
"publish": false,
"getPublishedVersion": false,
"assets": false
}
},
"packages": {
"core": {
"path": "./packages/core",
"manager": "javascript"
},
"action": {
"path": "./",
"path": "./packages/action",
"manager": "javascript",
"preversion": ["yarn", "yarn build"],
"getPublishedVersion": "git tag v${ pkgFile.version } 2> OUT= || echo ${ pkgFile.version }",
"publish": [
"git tag v${ pkgFile.versionMajor } -f",
"git tag v${ pkgFile.versionMajor }.${ pkgFile.versionMinor } -f",
"git push --tags -f"
"dependencies": [
"core"
]
}
}

View File

@@ -0,0 +1,5 @@
---
"action": minor
---
Update to Tauri beta release candidate.

View File

@@ -1,3 +0,0 @@
dist/
lib/
node_modules/

View File

@@ -1,58 +0,0 @@
{
"plugins": ["jest", "@typescript-eslint"],
"extends": ["plugin:github/es6"],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 9,
"sourceType": "module",
"project": "./tsconfig.json"
},
"rules": {
"eslint-comments/no-use": "off",
"import/no-namespace": "off",
"no-unused-vars": "off",
"@typescript-eslint/no-unused-vars": "error",
"@typescript-eslint/explicit-member-accessibility": ["error", {"accessibility": "no-public"}],
"@typescript-eslint/no-require-imports": "error",
"@typescript-eslint/array-type": "error",
"@typescript-eslint/await-thenable": "error",
"@typescript-eslint/ban-ts-ignore": "error",
"camelcase": "off",
"@typescript-eslint/camelcase": "error",
"@typescript-eslint/class-name-casing": "error",
"@typescript-eslint/explicit-function-return-type": ["error", {"allowExpressions": true}],
"@typescript-eslint/func-call-spacing": ["error", "never"],
"@typescript-eslint/generic-type-naming": ["error", "^[A-Z][A-Za-z]*$"],
"@typescript-eslint/no-array-constructor": "error",
"@typescript-eslint/no-empty-interface": "error",
"@typescript-eslint/no-explicit-any": "error",
"@typescript-eslint/no-extraneous-class": "error",
"@typescript-eslint/no-for-in-array": "error",
"@typescript-eslint/no-inferrable-types": "error",
"@typescript-eslint/no-misused-new": "error",
"@typescript-eslint/no-namespace": "error",
"@typescript-eslint/no-non-null-assertion": "warn",
"@typescript-eslint/no-object-literal-type-assertion": "error",
"@typescript-eslint/no-unnecessary-qualifier": "error",
"@typescript-eslint/no-unnecessary-type-assertion": "error",
"@typescript-eslint/no-useless-constructor": "error",
"@typescript-eslint/no-var-requires": "error",
"@typescript-eslint/prefer-for-of": "warn",
"@typescript-eslint/prefer-function-type": "warn",
"@typescript-eslint/prefer-includes": "error",
"@typescript-eslint/prefer-interface": "error",
"@typescript-eslint/prefer-string-starts-ends-with": "error",
"@typescript-eslint/promise-function-async": "error",
"@typescript-eslint/require-array-sort-compare": "error",
"@typescript-eslint/restrict-plus-operands": "error",
"semi": "off",
"@typescript-eslint/semi": ["error", "never"],
"@typescript-eslint/type-annotation-spacing": "error",
"@typescript-eslint/unbound-method": "error"
},
"env": {
"node": true,
"es6": true,
"jest/globals": true
}
}

View File

@@ -1,7 +1,6 @@
name: "test-action"
on:
push:
branches: [dev]
workflow_dispatch:
jobs:
build:
@@ -21,8 +20,6 @@ jobs:
uses: actions-rs/toolchain@v1
with:
toolchain: stable
- name: install tauri bundler
run: cargo install tauri-bundler --force
- name: install webkit2gtk (ubuntu only)
if: matrix.platform == 'ubuntu-latest'
run: |

71
.gitignore vendored
View File

@@ -1,7 +1,3 @@
# Dependency directory
node_modules
# Rest pulled from https://github.com/github/gitignore/blob/master/Node.gitignore
# Logs
logs
*.log
@@ -13,35 +9,8 @@ lerna-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# TypeScript v1 declaration files
@@ -50,8 +19,10 @@ typings/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
# Optional cache directory
.npm
.yarn
target
# Optional eslint cache
.eslintcache
@@ -69,31 +40,11 @@ typings/
.env
.env.test
# parcel-bundler cache (https://parceljs.org/)
.cache
# lockfiles, as a lib we don't need to lock
yarn.lock
# next.js build output
.next
# nuxt.js build output
.nuxt
# vuepress build output
.vuepress/dist
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# OS metadata
.DS_Store
Thumbs.db
# Ignore built ts files
__tests__/runner/*
lib/**/*
# rollup output
dist
# but we want the action dist
!packages/action/dist
!packages/action/dist/**

View File

@@ -1,3 +0,0 @@
dist/
lib/
node_modules/

View File

@@ -1,11 +0,0 @@
{
"printWidth": 80,
"tabWidth": 2,
"useTabs": false,
"semi": false,
"singleQuote": true,
"trailingComma": "none",
"bracketSpacing": false,
"arrowParens": "avoid",
"parser": "typescript"
}

View File

@@ -31,8 +31,6 @@ jobs:
uses: actions-rs/toolchain@v1
with:
toolchain: stable
- name: install tauri bundler
run: cargo install tauri-bundler --force
- name: install webkit2gtk (ubuntu only)
if: matrix.platform == 'ubuntu-latest'
run: |
@@ -72,16 +70,12 @@ jobs:
uses: actions-rs/toolchain@v1
with:
toolchain: stable
- name: install tauri bundler
run: cargo install tauri-bundler --force
- name: install webkit2gtk (ubuntu only)
if: matrix.platform == 'ubuntu-latest'
run: |
sudo apt-get update
sudo apt-get install -y webkit2gtk-4.0
- name: install app dependencies and build it
# If using the Vue CLI plugin, tauri:build will be run automatically by tauri-action
# and you can remove `&& yarn build` from this command
run: yarn && yarn build
- uses: tauri-apps/tauri-action@v0
env:
@@ -96,6 +90,8 @@ jobs:
## Uploading the artifacts to a release
Note that `actions/create-release` isn't maintained so you should find an alternative or let the Tauri Action handle the release.
```yml
name: "test-on-pr"
on: [pull_request]
@@ -113,7 +109,7 @@ jobs:
with:
node-version: 12
- name: get version
run: echo ::set-env name=PACKAGE_VERSION::$(node -p "require('./package.json').version")
run: echo "PACKAGE_VERSION=$(node -p "require('./package.json').version")" >> $GITHUB_ENV
- name: create release
id: create_release
uses: actions/create-release@v1.1.0
@@ -143,16 +139,12 @@ jobs:
uses: actions-rs/toolchain@v1
with:
toolchain: stable
- name: install tauri bundler
run: cargo install tauri-bundler --force
- name: install webkit2gtk (ubuntu only)
if: matrix.platform == 'ubuntu-latest'
run: |
sudo apt-get update
sudo apt-get install -y webkit2gtk-4.0
- name: install app dependencies and build it
# If using the Vue CLI plugin, tauri:build will be run automatically by tauri-action
# and you can remove `&& yarn build` from this command
run: yarn && yarn build
- uses: tauri-apps/tauri-action@v0
env:
@@ -192,5 +184,5 @@ jobs:
- You can use this Action on a repo that doesn't have Tauri configured. We automatically initialize Tauri before building, and configure it to use your Web artifacts.
- You can configure Tauri with the `configPath`, `distPath` and `iconPath` options.
- You can run custom NPM scripts with the `npmScript` option. So instead of running `yarn tauri build` or `npx tauri build`, we'll execute `yarn ${npmScript}`.
- Useful when you need custom build functionality when creating Tauri apps e.g. a `desktop:build` script.
- Useful when you need custom build functionality when creating Tauri apps e.g. a `desktop:build` script.
- When your app isn't on the root of the repo, use the `projectPath` input.

File diff suppressed because it is too large Load Diff

View File

@@ -7,20 +7,15 @@ license = ""
repository = ""
default-run = "app"
edition = "2018"
build = "src/build.rs"
[dependencies]
serde_json = "1.0"
serde = { version = "1.0", features = [ "derive" ] }
tauri = { version = "0.8", features = [ "all-api" ] }
tauri = { version = "1.0.0-beta-rc.2", features =["api-all"]}
[target."cfg(windows)".build-dependencies]
winres = "0.1"
[build-dependencies]
tauri-build = "1.0.0-beta-rc.0"
[features]
embedded-server = [ "tauri/embedded-server" ]
no-server = [ "tauri/no-server" ]
[[bin]]
name = "app"
path = "src/main.rs"
default = [ "custom-protocol" ]
custom-protocol = [ "tauri/custom-protocol" ]

View File

@@ -0,0 +1,3 @@
fn main() {
tauri_build::build()
}

View File

@@ -1,16 +0,0 @@
#[cfg(windows)]
extern crate winres;
#[cfg(windows)]
fn main() {
if std::path::Path::new("icons/icon.ico").exists() {
let mut res = winres::WindowsResource::new();
res.set_icon("icons/icon.ico");
res.compile().expect("Unable to find visual studio tools");
} else {
panic!("No Icon.ico found. Please add one or check the path");
}
}
#[cfg(not(windows))]
fn main() {}

View File

@@ -1,10 +0,0 @@
use serde::Deserialize;
#[derive(Deserialize)]
#[serde(tag = "cmd", rename_all = "camelCase")]
pub enum Cmd {
// your custom commands
// multiple arguments are allowed
// note that rename_all = "camelCase": you need to use "myCustomCommand" on JS
MyCustomCommand { argument: String },
}

View File

@@ -3,28 +3,8 @@
windows_subsystem = "windows"
)]
mod cmd;
fn main() {
tauri::AppBuilder::new()
.invoke_handler(|_webview, arg| {
use cmd::Cmd::*;
match serde_json::from_str(arg) {
Err(e) => {
Err(e.to_string())
}
Ok(command) => {
match command {
// definitions for your custom commands from Cmd here
MyCustomCommand { argument } => {
// your command code
println!("{}", argument);
}
}
Ok(())
}
}
})
.build()
.run();
tauri::Builder::default()
.run(tauri::generate_context!())
.expect("error while running tauri application");
}

View File

@@ -5,11 +5,7 @@
"beforeDevCommand": "",
"beforeBuildCommand": ""
},
"ctx": {},
"tauri": {
"embeddedServer": {
"active": true
},
"bundle": {
"active": true,
"targets": "all",
@@ -31,28 +27,27 @@
"depends": [],
"useBootstrapper": false
},
"osx": {
"macOS": {
"frameworks": [],
"minimumSystemVersion": "",
"useBootstrapper": false
},
"exceptionDomain": ""
"useBootstrapper": false,
"exceptionDomain": ""
}
},
"allowlist": {
"all": true
},
"window": {
"title": "Tauri App",
"width": 800,
"height": 600,
"resizable": true,
"fullscreen": false
},
"windows": [
{
"title": "Tauri App",
"width": 800,
"height": 600,
"resizable": true,
"fullscreen": false
}
],
"security": {
"csp": "default-src blob: data: filesystem: ws: http: https: 'unsafe-eval' 'unsafe-inline'"
},
"inliner": {
"active": true
}
}
}
}

11308
dist/index.js vendored

File diff suppressed because it is too large Load Diff

250
dist/main.js vendored
View File

@@ -1,250 +0,0 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const os_1 = require("os");
const core = __importStar(require("@actions/core"));
const execa_1 = __importDefault(require("execa"));
const path_1 = require("path");
const fs_1 = require("fs");
const upload_release_assets_1 = __importDefault(require("./upload-release-assets"));
const create_release_1 = __importDefault(require("./create-release"));
const toml_1 = __importDefault(require("@iarna/toml"));
function getPackageJson(root) {
const packageJsonPath = path_1.join(root, 'package.json');
if (fs_1.existsSync(packageJsonPath)) {
const packageJsonString = fs_1.readFileSync(packageJsonPath).toString();
const packageJson = JSON.parse(packageJsonString);
return packageJson;
}
return null;
}
function hasDependency(dependencyName, root) {
const packageJson = getPackageJson(root);
return (packageJson &&
((packageJson.dependencies && packageJson.dependencies[dependencyName]) ||
(packageJson.devDependencies &&
packageJson.devDependencies[dependencyName])));
}
function usesYarn(root) {
return fs_1.existsSync(path_1.join(root, 'yarn.lock'));
}
function execCommand(command, { cwd }) {
console.log(`running ${command}`);
const [cmd, ...args] = command.split(' ');
return execa_1.default(cmd, args, {
cwd,
shell: process.env.shell || true,
windowsHide: true,
stdio: 'inherit',
env: { FORCE_COLOR: '0' }
}).then();
}
function buildProject(root, debug, { configPath, distPath, iconPath, npmScript }) {
return __awaiter(this, void 0, void 0, function* () {
return new Promise(resolve => {
if (core.getInput('preferGlobal') === 'true') {
resolve('tauri');
}
else if (hasDependency('tauri', root) || hasDependency('vue-cli-plugin-tauri', root)) {
if (npmScript) {
resolve(usesYarn(root) ? `yarn ${npmScript}` : `npm run ${npmScript}`);
}
else {
resolve(usesYarn(root) ? 'yarn tauri' : 'npx tauri');
}
}
else {
execCommand('npm install -g tauri', { cwd: undefined }).then(() => resolve('tauri'));
}
})
.then((runner) => {
const manifestPath = path_1.join(root, 'src-tauri/Cargo.toml');
if (fs_1.existsSync(manifestPath)) {
const cargoManifest = toml_1.default.parse(fs_1.readFileSync(manifestPath).toString());
return {
runner,
name: cargoManifest.package.name,
version: cargoManifest.package.version
};
}
else {
const packageJson = getPackageJson(root);
const appName = packageJson
? (packageJson.displayName || packageJson.name).replace(/ /g, '-')
: 'app';
return execCommand(`${runner} init --ci --app-name ${appName}`, {
cwd: root
}).then(() => {
const cargoManifest = toml_1.default.parse(fs_1.readFileSync(manifestPath).toString());
const version = packageJson ? packageJson.version : '0.1.0';
console.log(`Replacing cargo manifest options - package.version=${version}`);
cargoManifest.package.version = version;
fs_1.writeFileSync(manifestPath, toml_1.default.stringify(cargoManifest));
const app = {
runner,
name: appName,
version
};
if (iconPath) {
return execCommand(`${runner} icon --i ${path_1.join(root, iconPath)}`, {
cwd: root
}).then(() => app);
}
return app;
});
}
})
.then((app) => {
const tauriConfPath = path_1.join(root, 'src-tauri/tauri.conf.json');
if (configPath !== null) {
fs_1.copyFileSync(configPath, tauriConfPath);
}
if (distPath) {
const tauriConf = JSON.parse(fs_1.readFileSync(tauriConfPath).toString());
tauriConf.build.distDir = distPath;
fs_1.writeFileSync(tauriConfPath, JSON.stringify(tauriConf));
}
const args = debug ? ['--debug'] : [];
const buildCommand = hasDependency('vue-cli-plugin-tauri', root)
? (usesYarn(root) ? 'yarn' : 'npm run') + ' tauri:build'
: `${app.runner} build`;
return execCommand(buildCommand + (args.length ? ` ${args.join(' ')}` : ''), { cwd: root })
.then(() => {
const appName = app.name;
const artifactsPath = path_1.join(root, `src-tauri/target/${debug ? 'debug' : 'release'}`);
switch (os_1.platform()) {
case 'darwin':
return [
path_1.join(artifactsPath, `bundle/dmg/${appName}_${app.version}_${process.arch}.dmg`),
path_1.join(artifactsPath, `bundle/osx/${appName}_${app.version}_${process.arch}.app`)
];
case 'win32':
return [
path_1.join(artifactsPath, `bundle/msi/${appName}_${app.version}_${process.arch}.msi`)
];
default:
const arch = process.arch === 'x64'
? 'amd64'
: process.arch === 'x32'
? 'i386'
: process.arch;
return [
path_1.join(artifactsPath, `bundle/deb/${appName}_${app.version}_${arch}.deb`),
path_1.join(artifactsPath, `bundle/appimage/${appName}_${app.version}_${arch}.AppImage`)
];
}
})
.then(paths => paths.filter(p => fs_1.existsSync(p)));
});
});
}
function run() {
return __awaiter(this, void 0, void 0, function* () {
try {
const projectPath = path_1.resolve(process.cwd(), core.getInput('projectPath') || process.argv[2]);
const configPath = path_1.join(projectPath, core.getInput('configPath') || 'tauri.conf.json');
const distPath = core.getInput('distPath');
const iconPath = core.getInput('iconPath');
const includeDebug = core.getInput('includeDebug') === 'true';
const npmScript = core.getInput('npmScript');
let tagName = core.getInput('tagName').replace('refs/tags/', '');
let releaseName = core.getInput('releaseName').replace('refs/tags/', '');
let body = core.getInput('releaseBody');
const draft = core.getInput('releaseDraft') === 'true';
const prerelease = core.getInput('prerelease') === 'true';
const commitish = core.getInput('releaseCommitish') || null;
if (Boolean(tagName) !== Boolean(releaseName)) {
throw new Error('`tag` is required along with `releaseName` when creating a release.');
}
const options = {
configPath: fs_1.existsSync(configPath) ? configPath : null,
distPath,
iconPath,
npmScript
};
const artifacts = yield buildProject(projectPath, false, options);
if (includeDebug) {
const debugArtifacts = yield buildProject(projectPath, true, options);
artifacts.push(...debugArtifacts);
}
if (artifacts.length === 0) {
throw new Error('No artifacts were found.');
}
console.log(`Artifacts: ${artifacts}.`);
let releaseId;
if (tagName) {
const packageJson = getPackageJson(projectPath);
const templates = [
{
key: '__VERSION__',
value: packageJson === null || packageJson === void 0 ? void 0 : packageJson.version
}
];
templates.forEach(template => {
const regex = new RegExp(template.key, 'g');
tagName = tagName.replace(regex, template.value);
releaseName = releaseName.replace(regex, template.value);
body = body.replace(regex, template.value);
});
const releaseData = yield create_release_1.default(tagName, releaseName, body, commitish || undefined, draft, prerelease);
releaseId = releaseData.id;
core.setOutput('releaseUploadUrl', releaseData.uploadUrl);
core.setOutput('releaseId', releaseData.id);
core.setOutput('releaseHtmlUrl', releaseData.htmlUrl);
}
else {
releaseId = Number(core.getInput('releaseId') || 0);
}
if (releaseId) {
if (os_1.platform() === 'darwin') {
let i = 0;
for (const artifact of artifacts) {
if (artifact.endsWith('.app')) {
yield execCommand(`tar -czf ${artifact}.tgz ${artifact}`, {
cwd: undefined
});
artifacts[i] += '.tgz';
}
i++;
}
}
yield upload_release_assets_1.default(releaseId, artifacts);
}
}
catch (error) {
console.log('this');
core.setFailed(error.message);
}
});
}
run();

View File

@@ -1,11 +0,0 @@
module.exports = {
clearMocks: true,
moduleFileExtensions: ['js', 'ts'],
testEnvironment: 'node',
testMatch: ['**/*.test.ts'],
testRunner: 'jest-circus/runner',
transform: {
'^.+\\.ts$': 'ts-jest'
},
verbose: true
}

View File

@@ -1,43 +1,8 @@
{
"name": "tauri-action",
"version": "0.0.10",
"description": "Tauri GitHub Action",
"main": "dist/index.js",
"scripts": {
"build": "tsc && ncc build dist/main.js -o dist",
"test": "jest"
},
"repository": {
"type": "git",
"url": "git+https://github.com/actions/typescript-action.git"
},
"keywords": [
"actions",
"node",
"setup"
],
"author": "Lucas Nogueira <lucas@tauri.studio>",
"license": "MIT",
"dependencies": {
"@actions/core": "^1.2.0",
"@actions/github": "^4.0.0",
"@iarna/toml": "^2.2.5",
"execa": "^5.0.0"
},
"devDependencies": {
"@types/jest": "26.0.22",
"@types/node": "14.14.37",
"@typescript-eslint/parser": "4.19.0",
"@zeit/ncc": "0.22.3",
"covector": "0.5.3",
"eslint": "7.23.0",
"eslint-plugin-github": "4.1.2",
"eslint-plugin-jest": "24.3.2",
"jest": "26.6.3",
"jest-circus": "26.6.3",
"js-yaml": "4.0.0",
"prettier": "2.2.1",
"ts-jest": "26.5.4",
"typescript": "4.2.3"
}
"private": true,
"workspaces": [
"packages/core",
"packages/cli",
"packages/action"
]
}

5
packages/action/dist/index.js vendored Normal file
View File

@@ -0,0 +1,5 @@
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
const src_1 = require("./src");
src_1.run();

4
packages/action/index.js Normal file
View File

@@ -0,0 +1,4 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const src_1 = require("./src");
src_1.run();

2
packages/action/index.ts Normal file
View File

@@ -0,0 +1,2 @@
import { run } from './src'
run()

View File

@@ -0,0 +1,31 @@
{
"name": "tauri-action",
"version": "0.0.10",
"description": "Tauri GitHub Action",
"author": "Lucas Nogueira <lucas@tauri.studio>",
"license": "MIT",
"main": "dist/index.js",
"scripts": {
"build": "rollup --config",
"prepublishOnly": "rollup --config"
},
"repository": {
"type": "git",
"url": "git+https://github.com/tauri-apps/tauri-action.git"
},
"keywords": [
"actions",
"tauri"
],
"dependencies": {
"@actions/core": "1.2.0",
"@actions/github": "4.0.0",
"@tauri-apps/action-core": "0.0.10"
},
"devDependencies": {
"@rollup/plugin-typescript": "8.2.1",
"rollup": "2.42.4",
"tslib": "2.1.0",
"typescript": "4.2.3"
}
}

View File

@@ -0,0 +1,24 @@
import typescript from "@rollup/plugin-typescript";
import pkg from "./package.json";
export default {
treeshake: true,
perf: true,
input: { index: "index.ts" },
output: {
dir: "dist",
format: "cjs",
entryFileNames: "[name].js",
exports: "named",
},
plugins: [typescript()],
external: [
...Object.keys(pkg.dependencies || {}),
"path",
],
watch: {
chokidar: true,
include: "src/**",
exclude: "node_modules/**",
},
};

View File

@@ -0,0 +1,108 @@
import { platform } from 'os'
import * as core from '@actions/core'
import { join, resolve } from 'path'
import { existsSync } from 'fs'
import uploadReleaseAssets from './upload-release-assets'
import createRelease from './create-release'
import { getPackageJson, buildProject, execCommand } from '@tauri-apps/action-core'
import type { BuildOptions } from '@tauri-apps/action-core'
export async function run(): Promise<void> {
try {
const preferGlobal = core.getInput('preferGlobal') === 'true'
const projectPath = resolve(
process.cwd(),
core.getInput('projectPath') || process.argv[2]
)
const configPath = join(
projectPath,
core.getInput('configPath') || 'tauri.conf.json'
)
const distPath = core.getInput('distPath')
const iconPath = core.getInput('iconPath')
const includeDebug = core.getInput('includeDebug') === 'true'
const npmScript = core.getInput('npmScript')
let tagName = core.getInput('tagName').replace('refs/tags/', '')
let releaseName = core.getInput('releaseName').replace('refs/tags/', '')
let body = core.getInput('releaseBody')
const draft = core.getInput('releaseDraft') === 'true'
const prerelease = core.getInput('prerelease') === 'true'
const commitish = core.getInput('releaseCommitish') || null
if (Boolean(tagName) !== Boolean(releaseName)) {
throw new Error(
'`tag` is required along with `releaseName` when creating a release.'
)
}
const options: BuildOptions = {
configPath: existsSync(configPath) ? configPath : null,
distPath,
iconPath,
npmScript
}
const artifacts = await buildProject(preferGlobal, projectPath, false, options)
if (includeDebug) {
const debugArtifacts = await buildProject(preferGlobal, projectPath, true, options)
artifacts.push(...debugArtifacts)
}
if (artifacts.length === 0) {
throw new Error('No artifacts were found.')
}
console.log(`Artifacts: ${artifacts}.`)
let releaseId: number
if (tagName) {
const packageJson = getPackageJson(projectPath)
const templates = [
{
key: '__VERSION__',
value: packageJson?.version
}
]
templates.forEach(template => {
const regex = new RegExp(template.key, 'g')
tagName = tagName.replace(regex, template.value)
releaseName = releaseName.replace(regex, template.value)
body = body.replace(regex, template.value)
})
const releaseData = await createRelease(
tagName,
releaseName,
body,
commitish || undefined,
draft,
prerelease
)
releaseId = releaseData.id
core.setOutput('releaseUploadUrl', releaseData.uploadUrl)
core.setOutput('releaseId', releaseData.id.toString())
core.setOutput('releaseHtmlUrl', releaseData.htmlUrl)
} else {
releaseId = Number(core.getInput('releaseId') || 0)
}
if (releaseId) {
if (platform() === 'darwin') {
let i = 0
for (const artifact of artifacts) {
if (artifact.endsWith('.app')) {
await execCommand(`tar -czf ${artifact}.tgz ${artifact}`, {
cwd: undefined
})
artifacts[i] += '.tgz'
}
i++
}
}
await uploadReleaseAssets(releaseId, artifacts)
}
} catch (error) {
core.setFailed(error.message)
}
}

View File

@@ -0,0 +1,12 @@
{
"compilerOptions": {
"target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
"outDir": "./dist", /* Redirect output structure to the directory. */
"rootDir": "./src", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
"strict": true, /* Enable all strict type-checking options. */
"noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
},
"exclude": ["node_modules", "**/*.test.ts"]
}

View File

@@ -0,0 +1,2 @@
const { run } = require('../dist')
run()

42
packages/cli/index.ts Normal file
View File

@@ -0,0 +1,42 @@
import { join, resolve } from 'path'
import { existsSync } from 'fs'
import { buildProject } from '@tauri-apps/action-core'
import type { BuildOptions } from '@tauri-apps/action-core'
import parseArgs from 'minimist'
export async function run(): Promise<void> {
const argv = parseArgs(process.argv.slice(2), {
string: ['project-path', 'config-path', 'dist-path', 'icon-path', 'npm-script'],
boolean: ['global-tauri', 'include-debug'],
default: {
'config-path': 'tauri.conf.json',
'project-path': '',
}
})
const preferGlobal = argv['global-tauri']
const projectPath = resolve(process.cwd(), argv['project-path'])
const configPath = join(projectPath, argv['config-path'])
const distPath = argv['dist-path']
const iconPath = argv['icon-path']
const includeDebug = argv['include-debug']
const npmScript = argv['npm-script']
const options: BuildOptions = {
configPath: existsSync(configPath) ? configPath : null,
distPath,
iconPath,
npmScript
}
const artifacts = await buildProject(preferGlobal, projectPath, false, options)
if (includeDebug) {
const debugArtifacts = await buildProject(preferGlobal, projectPath, true, options)
artifacts.push(...debugArtifacts)
}
if (artifacts.length === 0) {
throw new Error('No artifacts were found.')
}
console.log(`Artifacts: ${artifacts}.`)
}

27
packages/cli/package.json Normal file
View File

@@ -0,0 +1,27 @@
{
"name": "@tauri-apps/action-cli",
"version": "0.0.10",
"description": "Tauri GitHub Action CLI",
"author": "Lucas Nogueira <lucas@tauri.studio>",
"license": "MIT",
"main": "dist",
"scripts": {
"build": "rollup --config",
"prepublishOnly": "rollup --config"
},
"repository": {
"type": "git",
"url": "git+https://github.com/tauri-apps/tauri-action.git"
},
"dependencies": {
"@tauri-apps/action-core": "0.0.10",
"minimist": "1.2.5"
},
"devDependencies": {
"@rollup/plugin-typescript": "8.2.1",
"@types/minimist": "^1.2.1",
"rollup": "2.42.4",
"tslib": "2.1.0",
"typescript": "4.2.3"
}
}

View File

@@ -0,0 +1,24 @@
import typescript from "@rollup/plugin-typescript";
import pkg from "./package.json";
export default {
treeshake: true,
perf: true,
input: { index: "index.ts" },
output: {
dir: "dist",
format: "cjs",
entryFileNames: "[name].js",
exports: "named",
},
plugins: [typescript()],
external: [
...Object.keys(pkg.dependencies || {}),
"path",
],
watch: {
chokidar: true,
include: "src/**",
exclude: "node_modules/**",
},
};

View File

@@ -1,13 +1,10 @@
import {platform} from 'os'
import * as core from '@actions/core'
import { platform } from 'os'
import { readFileSync, existsSync, copyFileSync, writeFileSync } from 'fs'
import execa from 'execa'
import {join, resolve} from 'path'
import {readFileSync, existsSync, copyFileSync, writeFileSync} from 'fs'
import uploadReleaseAssets from './upload-release-assets'
import createRelease from './create-release'
import toml from '@iarna/toml'
import { join } from 'path'
function getPackageJson(root: string): any {
export function getPackageJson(root: string): any {
const packageJsonPath = join(root, 'package.json')
if (existsSync(packageJsonPath)) {
const packageJsonString = readFileSync(packageJsonPath).toString()
@@ -31,9 +28,9 @@ function usesYarn(root: string): boolean {
return existsSync(join(root, 'yarn.lock'))
}
function execCommand(
export function execCommand(
command: string,
{cwd}: {cwd: string | undefined}
{ cwd }: { cwd: string | undefined }
): Promise<void> {
console.log(`running ${command}`)
const [cmd, ...args] = command.split(' ')
@@ -42,7 +39,7 @@ function execCommand(
shell: process.env.shell || true,
windowsHide: true,
stdio: 'inherit',
env: {FORCE_COLOR: '0'}
env: { FORCE_COLOR: '0' }
}).then()
}
@@ -51,7 +48,7 @@ interface CargoManifestBin {
}
interface CargoManifest {
package: {version: string; name: string; 'default-run': string}
package: { version: string; name: string; 'default-run': string }
bin: CargoManifestBin[]
}
@@ -61,31 +58,32 @@ interface Application {
version: string
}
interface BuildOptions {
export interface BuildOptions {
configPath: string | null
distPath: string | null
iconPath: string | null
npmScript: string | null
}
async function buildProject(
export async function buildProject(
preferGlobal: boolean,
root: string,
debug: boolean,
{configPath, distPath, iconPath, npmScript}: BuildOptions
{ configPath, distPath, iconPath, npmScript }: BuildOptions
): Promise<string[]> {
return new Promise<string>(resolve => {
if (core.getInput('preferGlobal') === 'true') {
return new Promise<string>((resolve, reject) => {
if (preferGlobal) {
resolve('tauri')
} else if (hasDependency('tauri', root) || hasDependency('vue-cli-plugin-tauri', root)) {
} else if (hasDependency('@tauri-apps/cli', root) || hasDependency('vue-cli-plugin-tauri', root)) {
if (npmScript) {
resolve(usesYarn(root) ? `yarn ${npmScript}` : `npm run ${npmScript}`)
} else {
resolve(usesYarn(root) ? 'yarn tauri' : 'npx tauri')
}
} else {
execCommand('npm install -g tauri', {cwd: undefined}).then(() =>
execCommand('npm install -g @tauri-apps/cli', { cwd: undefined }).then(() =>
resolve('tauri')
)
).catch(reject)
}
})
.then((runner: string) => {
@@ -151,7 +149,7 @@ async function buildProject(
: `${app.runner} build`
return execCommand(
buildCommand + (args.length ? ` ${args.join(' ')}` : ''),
{cwd: root}
{ cwd: root }
)
.then(() => {
const appName = app.name
@@ -169,7 +167,7 @@ async function buildProject(
),
join(
artifactsPath,
`bundle/osx/${appName}_${app.version}_${process.arch}.app`
`bundle/macos/${appName}.app`
)
]
case 'win32':
@@ -184,8 +182,8 @@ async function buildProject(
process.arch === 'x64'
? 'amd64'
: process.arch === 'x32'
? 'i386'
: process.arch
? 'i386'
: process.arch
return [
join(
artifactsPath,
@@ -201,105 +199,3 @@ async function buildProject(
.then(paths => paths.filter(p => existsSync(p)))
})
}
async function run(): Promise<void> {
try {
const projectPath = resolve(
process.cwd(),
core.getInput('projectPath') || process.argv[2]
)
const configPath = join(
projectPath,
core.getInput('configPath') || 'tauri.conf.json'
)
const distPath = core.getInput('distPath')
const iconPath = core.getInput('iconPath')
const includeDebug = core.getInput('includeDebug') === 'true'
const npmScript = core.getInput('npmScript')
let tagName = core.getInput('tagName').replace('refs/tags/', '')
let releaseName = core.getInput('releaseName').replace('refs/tags/', '')
let body = core.getInput('releaseBody')
const draft = core.getInput('releaseDraft') === 'true'
const prerelease = core.getInput('prerelease') === 'true'
const commitish = core.getInput('releaseCommitish') || null
if (Boolean(tagName) !== Boolean(releaseName)) {
throw new Error(
'`tag` is required along with `releaseName` when creating a release.'
)
}
const options: BuildOptions = {
configPath: existsSync(configPath) ? configPath : null,
distPath,
iconPath,
npmScript
}
const artifacts = await buildProject(projectPath, false, options)
if (includeDebug) {
const debugArtifacts = await buildProject(projectPath, true, options)
artifacts.push(...debugArtifacts)
}
if (artifacts.length === 0) {
throw new Error('No artifacts were found.')
}
console.log(`Artifacts: ${artifacts}.`)
let releaseId: number
if (tagName) {
const packageJson = getPackageJson(projectPath)
const templates = [
{
key: '__VERSION__',
value: packageJson?.version
}
]
templates.forEach(template => {
const regex = new RegExp(template.key, 'g')
tagName = tagName.replace(regex, template.value)
releaseName = releaseName.replace(regex, template.value)
body = body.replace(regex, template.value)
})
const releaseData = await createRelease(
tagName,
releaseName,
body,
commitish || undefined,
draft,
prerelease
)
releaseId = releaseData.id
core.setOutput('releaseUploadUrl', releaseData.uploadUrl)
core.setOutput('releaseId', releaseData.id)
core.setOutput('releaseHtmlUrl', releaseData.htmlUrl)
} else {
releaseId = Number(core.getInput('releaseId') || 0)
}
if (releaseId) {
if (platform() === 'darwin') {
let i = 0
for (const artifact of artifacts) {
if (artifact.endsWith('.app')) {
await execCommand(`tar -czf ${artifact}.tgz ${artifact}`, {
cwd: undefined
})
artifacts[i] += '.tgz'
}
i++
}
}
await uploadReleaseAssets(releaseId, artifacts)
}
} catch (error) {
console.log('this')
core.setFailed(error.message)
}
}
run()

View File

@@ -0,0 +1,21 @@
{
"name": "@tauri-apps/action-core",
"version": "0.0.10",
"author": "Lucas Nogueira <lucas@tauri.studio>",
"license": "MIT",
"main": "dist",
"scripts": {
"build": "rollup --config",
"prepublishOnly": "rollup --config"
},
"dependencies": {
"@iarna/toml": "2.2.5",
"execa": "5.0.0"
},
"devDependencies": {
"@rollup/plugin-typescript": "8.2.1",
"rollup": "2.42.4",
"tslib": "2.1.0",
"typescript": "4.2.3"
}
}

View File

@@ -0,0 +1,24 @@
import typescript from "@rollup/plugin-typescript";
import pkg from "./package.json";
export default {
treeshake: true,
perf: true,
input: { index: "index.ts" },
output: {
dir: "dist",
format: "cjs",
entryFileNames: "[name].js",
exports: "named",
},
plugins: [typescript()],
external: [
...Object.keys(pkg.dependencies || {}),
"path",
],
watch: {
chokidar: true,
include: "src/**",
exclude: "node_modules/**",
},
};

View File

@@ -0,0 +1,8 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"outDir": "./dist",
"rootDir": "."
},
"include": ["index.ts"]
}

View File

@@ -1,12 +1,19 @@
{
"compilerOptions": {
"target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
"outDir": "./dist", /* Redirect output structure to the directory. */
"rootDir": "./src", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
"strict": true, /* Enable all strict type-checking options. */
"noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
"strict": true,
"module": "esnext",
"target": "es6",
"allowJs": true,
"pretty": true,
"esModuleInterop": true,
"resolveJsonModule": true,
"moduleResolution": "node",
"importHelpers": true
},
"exclude": ["node_modules", "**/*.test.ts"]
"baseUrl": ".",
"exclude": [
"__fixtures__",
"**/dist/**",
"**/bin/**"
]
}

5516
yarn.lock

File diff suppressed because it is too large Load Diff