feat(action) initialize

This commit is contained in:
Lucas Nogueira
2020-07-07 20:47:20 -03:00
parent a24dcb9d99
commit 5aca7f362e
14 changed files with 9369 additions and 6909 deletions

View File

@@ -1,27 +0,0 @@
import {wait} from '../src/wait'
import * as process from 'process'
import * as cp from 'child_process'
import * as path from 'path'
test('throws invalid number', async () => {
const input = parseInt('foo', 10)
await expect(wait(input)).rejects.toThrow('milliseconds not a number')
})
test('wait 500 ms', async () => {
const start = new Date()
await wait(500)
const end = new Date()
var delta = Math.abs(end.getTime() - start.getTime())
expect(delta).toBeGreaterThan(450)
})
// shows how the runner will run a javascript action with env / stdout protocol
test('test runs', () => {
process.env['INPUT_MILLISECONDS'] = '500'
const ip = path.join(__dirname, '..', 'lib', 'main.js')
const options: cp.ExecSyncOptions = {
env: process.env
}
console.log(cp.execSync(`node ${ip}`, options).toString())
})

View File

@@ -1,10 +1,18 @@
name: 'Your name here'
description: 'Provide a description here'
author: 'Your name or organization here'
author: 'Lucas Nogueira <lucas@tauri.studio>'
inputs:
myInput: # change this
description: 'input description here'
default: 'default value if applicable'
projectPath:
description: 'path to the root of the project that will be built'
default: '.'
configPath:
description: 'path to the tauri.conf.json file if you want a configuration different from the default one'
default: 'tauri.conf.json'
distPath:
description: 'path to the distributable folder with your index.html and JS/CSS'
outputs:
bundlePath:
description: 'path to the build artifact'
runs:
using: 'node12'
main: 'dist/index.js'
main: 'dist/main.js'

330
dist/index.js vendored
View File

@@ -1,330 +0,0 @@
module.exports =
/******/ (function(modules, runtime) { // webpackBootstrap
/******/ "use strict";
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ __webpack_require__.ab = __dirname + "/";
/******/
/******/ // the startup function
/******/ function startup() {
/******/ // Load entry module and return exports
/******/ return __webpack_require__(198);
/******/ };
/******/
/******/ // run startup
/******/ return startup();
/******/ })
/************************************************************************/
/******/ ({
/***/ 87:
/***/ (function(module) {
module.exports = require("os");
/***/ }),
/***/ 198:
/***/ (function(__unusedmodule, exports, __webpack_require__) {
"use strict";
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 __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const core = __importStar(__webpack_require__(470));
const wait_1 = __webpack_require__(521);
function run() {
return __awaiter(this, void 0, void 0, function* () {
try {
const ms = core.getInput('milliseconds');
core.debug(`Waiting ${ms} milliseconds ...`);
core.debug(new Date().toTimeString());
yield wait_1.wait(parseInt(ms, 10));
core.debug(new Date().toTimeString());
core.setOutput('time', new Date().toTimeString());
}
catch (error) {
core.setFailed(error.message);
}
});
}
run();
/***/ }),
/***/ 431:
/***/ (function(__unusedmodule, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const os = __webpack_require__(87);
/**
* Commands
*
* Command Format:
* ##[name key=value;key=value]message
*
* Examples:
* ##[warning]This is the user warning message
* ##[set-secret name=mypassword]definatelyNotAPassword!
*/
function issueCommand(command, properties, message) {
const cmd = new Command(command, properties, message);
process.stdout.write(cmd.toString() + os.EOL);
}
exports.issueCommand = issueCommand;
function issue(name, message) {
issueCommand(name, {}, message);
}
exports.issue = issue;
const CMD_PREFIX = '##[';
class Command {
constructor(command, properties, message) {
if (!command) {
command = 'missing.command';
}
this.command = command;
this.properties = properties;
this.message = message;
}
toString() {
let cmdStr = CMD_PREFIX + this.command;
if (this.properties && Object.keys(this.properties).length > 0) {
cmdStr += ' ';
for (const key in this.properties) {
if (this.properties.hasOwnProperty(key)) {
const val = this.properties[key];
if (val) {
// safely append the val - avoid blowing up when attempting to
// call .replace() if message is not a string for some reason
cmdStr += `${key}=${escape(`${val || ''}`)};`;
}
}
}
}
cmdStr += ']';
// safely append the message - avoid blowing up when attempting to
// call .replace() if message is not a string for some reason
const message = `${this.message || ''}`;
cmdStr += escapeData(message);
return cmdStr;
}
}
function escapeData(s) {
return s.replace(/\r/g, '%0D').replace(/\n/g, '%0A');
}
function escape(s) {
return s
.replace(/\r/g, '%0D')
.replace(/\n/g, '%0A')
.replace(/]/g, '%5D')
.replace(/;/g, '%3B');
}
//# sourceMappingURL=command.js.map
/***/ }),
/***/ 470:
/***/ (function(__unusedmodule, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const command_1 = __webpack_require__(431);
const path = __webpack_require__(622);
/**
* The code to exit an action
*/
var ExitCode;
(function (ExitCode) {
/**
* A code indicating that the action was successful
*/
ExitCode[ExitCode["Success"] = 0] = "Success";
/**
* A code indicating that the action was a failure
*/
ExitCode[ExitCode["Failure"] = 1] = "Failure";
})(ExitCode = exports.ExitCode || (exports.ExitCode = {}));
//-----------------------------------------------------------------------
// Variables
//-----------------------------------------------------------------------
/**
* sets env variable for this action and future actions in the job
* @param name the name of the variable to set
* @param val the value of the variable
*/
function exportVariable(name, val) {
process.env[name] = val;
command_1.issueCommand('set-env', { name }, val);
}
exports.exportVariable = exportVariable;
/**
* exports the variable and registers a secret which will get masked from logs
* @param name the name of the variable to set
* @param val value of the secret
*/
function exportSecret(name, val) {
exportVariable(name, val);
command_1.issueCommand('set-secret', {}, val);
}
exports.exportSecret = exportSecret;
/**
* Prepends inputPath to the PATH (for this action and future actions)
* @param inputPath
*/
function addPath(inputPath) {
command_1.issueCommand('add-path', {}, inputPath);
process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`;
}
exports.addPath = addPath;
/**
* Gets the value of an input. The value is also trimmed.
*
* @param name name of the input to get
* @param options optional. See InputOptions.
* @returns string
*/
function getInput(name, options) {
const val = process.env[`INPUT_${name.replace(' ', '_').toUpperCase()}`] || '';
if (options && options.required && !val) {
throw new Error(`Input required and not supplied: ${name}`);
}
return val.trim();
}
exports.getInput = getInput;
/**
* Sets the value of an output.
*
* @param name name of the output to set
* @param value value to store
*/
function setOutput(name, value) {
command_1.issueCommand('set-output', { name }, value);
}
exports.setOutput = setOutput;
//-----------------------------------------------------------------------
// Results
//-----------------------------------------------------------------------
/**
* Sets the action status to failed.
* When the action exits it will be with an exit code of 1
* @param message add error issue message
*/
function setFailed(message) {
process.exitCode = ExitCode.Failure;
error(message);
}
exports.setFailed = setFailed;
//-----------------------------------------------------------------------
// Logging Commands
//-----------------------------------------------------------------------
/**
* Writes debug message to user log
* @param message debug message
*/
function debug(message) {
command_1.issueCommand('debug', {}, message);
}
exports.debug = debug;
/**
* Adds an error issue
* @param message error issue message
*/
function error(message) {
command_1.issue('error', message);
}
exports.error = error;
/**
* Adds an warning issue
* @param message warning issue message
*/
function warning(message) {
command_1.issue('warning', message);
}
exports.warning = warning;
//# sourceMappingURL=core.js.map
/***/ }),
/***/ 521:
/***/ (function(__unusedmodule, exports) {
"use strict";
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());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
function wait(milliseconds) {
return __awaiter(this, void 0, void 0, function* () {
return new Promise(resolve => {
if (isNaN(milliseconds)) {
throw new Error('milliseconds not a number');
}
setTimeout(() => resolve('done!'), milliseconds);
});
});
}
exports.wait = wait;
/***/ }),
/***/ 622:
/***/ (function(module) {
module.exports = require("path");
/***/ })
/******/ });

135
dist/main.js vendored Normal file
View File

@@ -0,0 +1,135 @@
"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.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");
function hasTauriDependency(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);
if (packageJson.dependencies && packageJson.dependencies.tauri) {
return true;
}
}
return false;
}
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, args, { configPath, distPath }) {
return __awaiter(this, void 0, void 0, function* () {
return new Promise((resolve) => {
if (hasTauriDependency(root)) {
const runner = usesYarn(root) ? 'yarn tauri' : 'npx tauri';
resolve(runner);
}
else {
execCommand('npm install -g tauri', { cwd: undefined }).then(() => resolve('tauri'));
}
})
.then((runner) => {
if (fs_1.existsSync(path_1.join(root, 'src-tauri'))) {
return runner;
}
else {
return execCommand(`${runner} init`, { cwd: root }).then(() => runner);
}
})
.then((runner) => {
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));
}
return execCommand(`${runner} build` + (args.length ? ` ${args.join(' ')}` : ''), { cwd: root }).then(() => {
const appName = 'app';
const artifactsPath = path_1.join(root, 'src-tauri/target/release');
switch (os_1.platform()) {
case 'darwin':
return [
path_1.join(artifactsPath, `bundle/dmg/${appName}.dmg`),
path_1.join(artifactsPath, `bundle/osx/${appName}.osx`)
];
case 'win32':
return [
path_1.join(artifactsPath, `bundle/${appName}.msi`),
];
default:
return [
path_1.join(artifactsPath, `bundle/deb/${appName}.deb`),
path_1.join(artifactsPath, `bundle/appimage/${appName}.AppImage`)
];
}
});
});
});
}
function run() {
return __awaiter(this, void 0, void 0, function* () {
try {
const projectPath = core.getInput('projectPath') || process.argv[2];
const configPath = path_1.join(projectPath, core.getInput('configPath') || 'tauri.conf.json');
const distPath = core.getInput('distPath');
let config = null;
if (fs_1.existsSync(configPath)) {
config = JSON.parse(fs_1.readFileSync(configPath).toString());
}
const artifacts = yield buildProject(projectPath, [], { configPath: config, distPath });
console.log(`artifacts: ${artifacts}`);
core.setOutput('artifacts', artifacts);
}
catch (error) {
core.setFailed(error.message);
}
});
}
run();

2
example/.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
src-tauri
dist/index.tauri.html

8
example/dist/index.html vendored Normal file
View File

@@ -0,0 +1,8 @@
<!DOCTYPE html>
<html>
<body>
<div>Test Application</div>
</body>
</html>

14
example/package.json Normal file
View File

@@ -0,0 +1,14 @@
{
"name": "example",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "MIT",
"dependencies": {
"tauri": "^0.8.1"
}
}

4069
example/yarn.lock Normal file

File diff suppressed because it is too large Load Diff

6523
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,9 +1,8 @@
{
"name": "typescript-action",
"version": "0.0.0",
"private": true,
"description": "TypeScript template action",
"main": "lib/main.js",
"name": "tauri-action",
"version": "0.0.1",
"description": "Tauri GitHub Action",
"main": "dist/index.js",
"scripts": {
"build": "tsc",
"format": "prettier --write **/*.ts",
@@ -22,10 +21,11 @@
"node",
"setup"
],
"author": "YourNameOrOrganization",
"author": "Lucas Nogueira <lucas@tauri.studio>",
"license": "MIT",
"dependencies": {
"@actions/core": "^1.2.0"
"@actions/core": "^1.2.0",
"execa": "^4.0.3"
},
"devDependencies": {
"@types/jest": "^24.0.23",

View File

@@ -1,16 +1,103 @@
import { platform } from 'os';
import * as core from '@actions/core'
import {wait} from './wait'
import execa from 'execa'
import { join } from 'path'
import { readFileSync, existsSync, copyFileSync, writeFileSync } from 'fs'
function hasTauriDependency(root: string): boolean {
const packageJsonPath = join(root, 'package.json')
if (existsSync(packageJsonPath)) {
const packageJsonString = readFileSync(packageJsonPath).toString()
const packageJson = JSON.parse(packageJsonString)
if (packageJson.dependencies && packageJson.dependencies.tauri) {
return true
}
}
return false
}
function usesYarn(root: string): boolean {
return existsSync(join(root, 'yarn.lock'))
}
function execCommand(command: string, { cwd }: { cwd: string | undefined }): Promise<void> {
console.log(`running ${command}`)
const [cmd, ...args] = command.split(' ')
return execa(cmd, args, {
cwd,
shell: process.env.shell || true,
windowsHide: true,
stdio: 'inherit',
env: { FORCE_COLOR: '0' },
}).then()
}
async function buildProject(root: string, args: string[], { configPath, distPath }: { configPath: string | null, distPath: string | null }): Promise<string[]> {
return new Promise<string>((resolve) => {
if (hasTauriDependency(root)) {
const runner = usesYarn(root) ? 'yarn tauri' : 'npx tauri'
resolve(runner)
} else {
execCommand('npm install -g tauri', { cwd: undefined }).then(() => resolve('tauri'))
}
})
.then((runner: string) => {
if (existsSync(join(root, 'src-tauri'))) {
return runner
} else {
return execCommand(`${runner} init`, { cwd: root }).then(() => runner)
}
})
.then((runner: string) => {
const tauriConfPath = join(root, 'src-tauri/tauri.conf.json')
if (configPath !== null) {
copyFileSync(configPath, tauriConfPath)
}
if (distPath) {
const tauriConf = JSON.parse(readFileSync(tauriConfPath).toString())
tauriConf.build.distDir = distPath
writeFileSync(tauriConfPath, JSON.stringify(tauriConf))
}
return execCommand(`${runner} build` + (args.length ? ` ${args.join(' ')}` : ''), { cwd: root }).then(() => {
const appName = 'app'
const artifactsPath = join(root, 'src-tauri/target/release')
switch (platform()) {
case 'darwin':
return [
join(artifactsPath, `bundle/dmg/${appName}.dmg`),
join(artifactsPath, `bundle/osx/${appName}.osx`)
]
case 'win32':
return [
join(artifactsPath, `bundle/${appName}.msi`),
]
default:
return [
join(artifactsPath, `bundle/deb/${appName}.deb`),
join(artifactsPath, `bundle/appimage/${appName}.AppImage`)
]
}
})
})
}
async function run(): Promise<void> {
try {
const ms: string = core.getInput('milliseconds')
core.debug(`Waiting ${ms} milliseconds ...`)
const projectPath = core.getInput('projectPath') || process.argv[2]
const configPath = join(projectPath, core.getInput('configPath') || 'tauri.conf.json')
const distPath = core.getInput('distPath')
core.debug(new Date().toTimeString())
await wait(parseInt(ms, 10))
core.debug(new Date().toTimeString())
let config = null
if (existsSync(configPath)) {
config = JSON.parse(readFileSync(configPath).toString())
}
core.setOutput('time', new Date().toTimeString())
const artifacts = await buildProject(projectPath, [], { configPath: config, distPath })
console.log(`artifacts: ${artifacts}`)
core.setOutput('artifacts', artifacts)
} catch (error) {
core.setFailed(error.message)
}

View File

@@ -1,9 +0,0 @@
export async function wait(milliseconds: number): Promise<string> {
return new Promise(resolve => {
if (isNaN(milliseconds)) {
throw new Error('milliseconds not a number')
}
setTimeout(() => resolve('done!'), milliseconds)
})
}

View File

@@ -2,7 +2,7 @@
"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": "./lib", /* Redirect output structure to the directory. */
"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. */

5026
yarn.lock Normal file

File diff suppressed because it is too large Load Diff