Compare commits

...
11 Commits
Author SHA1 Message Date
shmyga 1339ba0c98 ci(version): 1.2.0
test / test (push) Successful in 45s
release / release (push) Failing after 37s
2026-10-24 18:57:08 +03:00
shmyga c63417cefa ci(gitea): add gitea workflows
test / test (push) Successful in 47s
2026-10-24 18:56:28 +03:00
shmyga a25f223b61 refactor: fix typescript errors 2026-10-22 23:18:06 +03:00
shmyga 84d905dbb3 refactor: refork tail module 2026-10-22 12:04:40 +03:00
shmyga a421d56ec1 refactor: format log.ts 2026-10-20 00:54:16 +03:00
shmyga 079cf9d52d refactor: remove time-stamp dependency 2026-10-20 00:37:23 +03:00
shmyga 0edfb12473 test: add tests 2026-10-16 00:43:09 +03:00
shmyga c3c0b07d32 ci(version): 1.1.1
release / release (push) Failing after 37s
2026-10-14 19:35:14 +03:00
shmyga ec3d3b547c build(npm): add template dir to files section 2026-10-14 19:34:56 +03:00
shmyga 3f23c6973b ci(version): 1.1.0
release / release (push) Failing after 51s
2026-10-14 15:58:11 +03:00
shmyga dba24a2c68 feat(project): add preset 2026-10-14 15:53:44 +03:00
48 changed files with 4105 additions and 5165 deletions
+3 -13
View File
@@ -4,27 +4,17 @@ on:
push: push:
tags: ["*"] tags: ["*"]
env:
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
jobs: jobs:
release: release:
runs-on: ubuntu-latest runs-on: ubuntu-latest
permissions:
contents: read
id-token: write
steps: steps:
- uses: actions/checkout@v7 - uses: actions/checkout@v7
- run: echo '' > requirements.txt - run: echo '' > requirements.txt
- uses: https://git.shmyga.ru/InfernalGames/project-manager@master - uses: https://git.shmyga.ru/InfernalGames/project-manager@master
- run: pm setup:npm -vv
- run: pm build:npm -vv
- uses: actions/setup-node@v7
with: with:
node-version: "24.x" setup-nodejs: true
registry-url: "https://registry.npmjs.org" - run: pm build -vv
#- run: pm publish:npm -vv
#- run: npm config set //registry.npmjs.org/:_authToken "$NPM_TOKEN" #- run: npm config set //registry.npmjs.org/:_authToken "$NPM_TOKEN"
- run: npm publish --provenance --access public - run: npm publish --provenance --access public
env: env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
+16
View File
@@ -0,0 +1,16 @@
name: test
on: push
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- run: echo '' > requirements.txt
- uses: https://git.shmyga.ru/InfernalGames/project-manager@master
with:
setup-nodejs: true
- run: pm build -vv
- run: pm lint -vv
- run: pm test -vv
+2
View File
@@ -1,5 +1,7 @@
# Gulp HaXe Tool # Gulp HaXe Tool
[![test](https://git.shmyga.ru/InfernalGames/gulp-haxetool/actions/workflows/test.yaml/badge.svg?branch=master)](https://git.shmyga.ru/InfernalGames/gulp-haxetool/actions?workflow=test.yaml)
## Introducing ## Introducing
### Dignity ### Dignity
+2773 -4164
View File
File diff suppressed because it is too large Load Diff
+36 -20
View File
@@ -1,19 +1,21 @@
{ {
"name": "gulp-haxetool", "name": "gulp-haxetool",
"type": "module", "type": "module",
"version": "1.0.0", "version": "1.2.0",
"description": "HaXe Tool for Gulp", "description": "HaXe Tool for Gulp",
"exports": { "exports": {
".": "./dist/index.mjs", ".": "./dist/index.mjs",
"./package.json": "./package.json" "./package.json": "./package.json"
}, },
"files": [ "files": [
"template",
"dist" "dist"
], ],
"scripts": { "scripts": {
"build": "tsdown", "build": "tsdown",
"dev": "tsdown --watch", "dev": "tsdown --watch",
"typecheck": "tsc --noEmit" "lint": "tsc --noEmit",
"test": "node --test"
}, },
"repository": { "repository": {
"type": "git", "type": "git",
@@ -29,40 +31,54 @@
"dependencies": { "dependencies": {
"ansi-colors": "^1.1.0", "ansi-colors": "^1.1.0",
"async": "^2.6.0", "async": "^2.6.0",
"cli-progress": "^3.0.0", "cli-progress": "^3.12.0",
"dateformat": "^5.0.4",
"fancy-log": "^1.3.2", "fancy-log": "^1.3.2",
"fs-extra": "^5.0.0", "fs-extra": "^5.0.0",
"got": "^9.6.0", "got": "^16.1.0",
"gulp": "^4.0.0", "gulp": "^5.0.1",
"gulp-clean": "^0.4.0",
"gulp-connect": "^5.7.0",
"gulp-debian": "^0.1.9", "gulp-debian": "^0.1.9",
"gulp-gzip": "^1.4.2", "gulp-gzip": "^1.4.2",
"gulp-rename": "^1.2.2", "gulp-rename": "^2.1.0",
"gulp-spawn": "^0.4.0", "gulp-tar": "^5.0.0",
"gulp-tar": "^3.0.0", "gulp-zip": "^6.1.0",
"gulp-webserver": "^0.9.1",
"gulp-zip": "^5.0.0",
"lodash.defaults": "^4.2.0", "lodash.defaults": "^4.2.0",
"lodash.template": "^4.4.0", "lodash.template": "^4.4.0",
"plugin-error": "^1.0.1", "plugin-error": "^1.0.1",
"promise-streams": "^2.1.1", "promise-streams": "^2.1.1",
"tail": "^1.2.3", "tail": "^2.2.6",
"tar": "^4.4.10", "tar": "^7.5.22",
"through2": "^2.0.3", "through2": "^5.0.12",
"time-stamp": "^1.1.0",
"tmp-file": "^2.0.1", "tmp-file": "^2.0.1",
"unzip-stream": "^0.3.0", "unzip-stream": "^0.3.4",
"vinyl": "^2.1.0", "vinyl": "^3.0.1",
"vinyl-fs": "^3.0.2" "vinyl-fs": "^4.0.2"
}, },
"devDependencies": { "devDependencies": {
"@types/async": "^3.2.26",
"@types/cli-progress": "^3.11.6",
"@types/dateformat": "^5.0.3",
"@types/fs-extra": "^11.0.4", "@types/fs-extra": "^11.0.4",
"@types/gulp": "^4.0.18",
"@types/gulp-connect": "^5.0.10",
"@types/gulp-gzip": "^0.0.36",
"@types/gulp-rename": "^2.0.7", "@types/gulp-rename": "^2.0.7",
"@types/gulp-tar": "^4.0.1",
"@types/gulp-zip": "^4.0.4",
"@types/lodash.template": "^4.5.3", "@types/lodash.template": "^4.5.3",
"@types/node": "^26.1.1", "@types/node": "^26.6.5",
"@types/vinyl-fs": "^3.0.8", "@types/tail": "^2.2.3",
"eslint": "^10.12.0", "@types/tar": "^7.0.87",
"@types/through2": "^5.0.0",
"@types/unzip-stream": "^0.3.4",
"eslint": "^10.13.0",
"prettier": "^3.9.10", "prettier": "^3.9.10",
"tsdown": "0.22.14", "tsdown": "0.22.14",
"typescript": "^7.0.2" "typescript": "^7.0.2"
},
"inlinedDependencies": {
"lodash": "4.18.1"
} }
} }
+9
View File
@@ -0,0 +1,9 @@
declare module "gulp-clean" {
import type { WritableStream } from "stream";
export interface Options {
force?: boolean;
}
export default (options?: Options) => WritableStream;
}
+32
View File
@@ -0,0 +1,32 @@
declare module "gulp-debian" {
import type { WritableStream } from "stream";
export interface Options {
package: string;
version: string;
section: string;
priority: string;
architecture: string;
maintainer?: string;
description?: string;
preinst?: string[];
postinst?: string[];
prerm?: string[];
postrm?: string[];
conffiles?: string;
changelog?: {
version: string;
distribution: string;
urgency: string;
date: Date;
changes: string[];
}[];
_target?: string;
_out?: string;
_copyright?: string;
_clean?: boolean;
_verbose?: boolean;
}
export default (options: Options) => WritableStream;
}
+14
View File
@@ -0,0 +1,14 @@
declare module "vinyl" {
export class File {
path: string;
cwd: string;
base: string;
contents: any;
stat: any;
history: any[];
constructor(params: any);
clone(options?: any);
}
export default File;
}
+84
View File
@@ -0,0 +1,84 @@
import progress from "cli-progress";
import fs from "fs";
import fse from "fs-extra";
import got from "got";
import path from "path";
import ps from "promise-streams";
import type { Stream, Writable } from "stream";
import * as tar from "tar";
import unzip from "unzip-stream";
export class Downloader {
static bar: progress.MultiBar | null;
static createProgressBar() {
if (Downloader.bar == null) {
Downloader.bar = new progress.MultiBar(
{
clearOnComplete: true,
},
progress.Presets.shades_grey,
);
}
return Downloader.bar.create(0, 0);
}
static releaseProgressBar(bar: progress.SingleBar) {
bar.stop();
if (Downloader.bar != null) {
Downloader.bar.remove(bar);
if (!Downloader.bar.isActive) {
Downloader.bar.stop();
Downloader.bar = null;
}
}
}
static download(url: string, dest: string, strip = 1, executable = false) {
fse.ensureDirSync(dest);
const bar = Downloader.createProgressBar();
let stream: Stream = got.stream(url);
stream = stream
.on("request", (r: any) => {
if (bar) bar.start(1, 0);
})
.on("downloadProgress", (p: any) => {
if (bar) {
bar.setTotal(p.total);
bar.update(p.transferred);
if (p.total === p.transferred) {
Downloader.releaseProgressBar(bar);
}
}
});
if (url.endsWith(".zip")) {
stream = stream.pipe(unzip.Parse()).on("entry", (entry: any) => {
const filePath = entry.path.split("/").slice(strip).join(path.sep);
if (filePath.length > 0) {
if (entry.type === "Directory") {
fse.ensureDirSync(path.join(dest, path.normalize(filePath)));
} else if (entry.type === "File") {
const fullFilePath = path.join(dest, path.normalize(filePath));
const dirPath = path.dirname(fullFilePath);
if (!fs.existsSync(dirPath)) {
fse.ensureDirSync(dirPath);
}
entry.pipe(
fs.createWriteStream(path.join(dest, path.normalize(filePath)), {
// ToDo: zip entry file mode?
mode: executable ? 0o755 : undefined,
}),
);
}
} else {
entry.autodrain();
}
});
} else if (url.endsWith("tar.gz")) {
stream = stream.pipe(tar.x({ C: dest, strip }) as unknown as Writable);
} else {
stream = stream.pipe(fs.createWriteStream(path.join(dest, url.split("/").pop()!)));
}
return ps.wait(stream);
}
}
+19 -17
View File
@@ -1,5 +1,4 @@
import colors from "ansi-colors"; import colors from "ansi-colors";
import timestamp from "time-stamp";
const Level = { const Level = {
VERBOSE: -1, VERBOSE: -1,
@@ -11,24 +10,27 @@ const Level = {
const level = process.argv.indexOf("--verbose") > -1 ? Level.VERBOSE : Level.INFO; const level = process.argv.indexOf("--verbose") > -1 ? Level.VERBOSE : Level.INFO;
const formatTime = (date: Date): string => date.toTimeString().split(" ")[0];
export class Log { export class Log {
static level = level; static level = level;
static colorPatterns: [string, (m: string) => string][] = [
static colorize(pattern: string) {
for (const item of [
["_", colors.cyan], ["_", colors.cyan],
["\\*", colors.magenta], ["\\*", colors.magenta],
["!", colors.red], ["!", colors.red],
]) { ];
static colorize(pattern: string) {
for (const item of this.colorPatterns) {
const r = new RegExp(item[0] + "(.*?)" + item[0], "g"); const r = new RegExp(item[0] + "(.*?)" + item[0], "g");
pattern = pattern.replace(r, item[1]("$1")); pattern = pattern.replace(r, item[1]("$1"));
} }
return pattern; return pattern;
} }
static write(level: number, tag: string, pattern: string, ...args: any) { static write(level: number, tag: string, pattern: string, args: any[]) {
if (level >= this.level) { if (level >= this.level) {
const message = `[${colors.gray(timestamp("HH:mm:ss"))}] ${colors.green(tag)} ${this.colorize(pattern)}`; const message = `[${colors.gray(formatTime(new Date()))}] ${colors.green(tag)} ${this.colorize(pattern)}`;
console.log(message, ...args); console.log(message, ...args);
} }
} }
@@ -39,23 +41,23 @@ export class Log {
this.tag = tag; this.tag = tag;
} }
v(...args: any) { v(message: string, ...args: any) {
Log.write(-1, this.tag, ...args); Log.write(-1, this.tag, message, args);
} }
d(...args: any) { d(message: string, ...args: any) {
Log.write(0, this.tag, ...args); Log.write(0, this.tag, message, args);
} }
i(...args: any) { i(message: string, ...args: any) {
Log.write(1, this.tag, ...args); Log.write(1, this.tag, message, args);
} }
w(...args: any) { w(message: string, ...args: any) {
Log.write(2, this.tag, ...args); Log.write(2, this.tag, message, args);
} }
e(...args: any) { e(message: string, ...args: any) {
Log.write(3, this.tag, ...args); Log.write(3, this.tag, message, args);
} }
} }
+28 -45
View File
@@ -1,48 +1,25 @@
import { Transform, Writable } from "stream"; import { Transform, Writable, type TransformCallback, type WritableOptions } from "stream";
import { StringDecoder } from "string_decoder"; import { StringDecoder } from "string_decoder";
import { Tail } from "tail";
import through from "through2";
import Vinyl from "vinyl";
export class TailVinyl extends Vinyl { export type TailHandler = (line: string) => void;
constructor(params: any) {
params.contents = new Transform();
super(params);
if (params.path) {
this.tail = new Tail(params.path);
(this.tail.on("line", (line) => {
if (params.handler) {
line = params.handler(line);
}
if (line) {
this.contents.write(line + "\n");
}
}),
this.tail.on("error", (error: any) => this.contents.write("error: " + error)));
}
}
dispose() { export class HandlerWriter extends Writable {
if (this.tail) { private handler: any;
this.tail.unwatch(); private decoder: StringDecoder;
} private data: string;
this.contents.destroy();
}
}
export class StringWritable extends Writable { constructor(handler: TailHandler, options?: WritableOptions) {
constructor(handler: any, options?: any) { if (!options) options = {};
options.objectMode = true;
super(options); super(options);
this.handler = handler; this.handler = handler;
const state = this._writableState; this.decoder = new StringDecoder(options?.defaultEncoding);
this._decoder = new StringDecoder(state.defaultEncoding);
this.data = ""; this.data = "";
} }
_write(chunk, encoding, callback) { _write(chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void {
if (encoding === "buffer") { chunk = this.decoder.write(chunk);
chunk = this._decoder.write(chunk); for (const line of chunk.split("\n")) {
for (const line of chunk.split("\n"))
if (line.length) { if (line.length) {
this.handler(line); this.handler(line);
} }
@@ -51,18 +28,24 @@ export class StringWritable extends Writable {
callback(); callback();
} }
_final(callback) { _final(callback: (error?: Error | null) => void): void {
this.data += this._decoder.end(); this.data += this.decoder.end();
callback(); callback();
} }
} }
export const tail = (handler: any) => { export class TailTransform extends Transform {
return through.obj(function (file: any, enc: string, callback: any) { constructor(private handler: TailHandler) {
if (file.contents && file.contents.pipe) { super({ objectMode: true });
file.contents.pipe(new StringWritable(handler));
} }
this.push(file);
_transform(chunk: any, encoding: BufferEncoding, callback: TransformCallback): void {
if (chunk.contents && chunk.contents.pipe) {
chunk.contents.pipe(new HandlerWriter(this.handler));
}
this.push(chunk);
callback(); callback();
}); }
}; }
export const tail = (handler: TailHandler) => new TailTransform(handler);
+6
View File
@@ -0,0 +1,6 @@
export const streamToPromise = (stream: any) => {
return new Promise((resolve, reject) => {
stream.on("end", resolve);
stream.on("error", reject);
});
};
+65
View File
@@ -0,0 +1,65 @@
import { Transform, type TransformCallback } from "stream";
import { Tail } from "tail";
import Vinyl from "vinyl";
export type WatchHandler = (line: string) => string | undefined;
export interface WatchParams {
source: string;
handler?: WatchHandler;
}
class BufferingTransform extends Transform {
_transform(chunk: any, encoding: BufferEncoding, callback: TransformCallback): void {
this.push(chunk);
callback();
}
}
export class TailVinyl extends Vinyl {
private tail?: Tail;
constructor(params: WatchParams) {
super({ path: "out.log", contents: new BufferingTransform() });
if (params.source) {
this.tail = new Tail(params.source);
this.tail.on("line", (line) => {
if (params.handler) {
line = params.handler(line);
}
if (line) {
this.contents.write(line + "\n");
}
});
this.tail.on("error", (error) => this.contents.write("error: " + error));
}
}
clone() {
return new Vinyl({
cwd: this.cwd,
base: this.base,
history: this.history.slice(),
contents: this.contents,
});
}
dispose() {
this.tail?.unwatch();
this.contents.destroy();
}
}
export class WatchVinylTransform extends Transform {
constructor(private params: WatchParams) {
super({ objectMode: true });
}
_transform(chunk: any, encoding: BufferEncoding, callback: TransformCallback): void {
const log = new TailVinyl(this.params);
this.on("end", () => log.dispose());
this.push(log);
callback();
}
}
export const watch = (source: string, handler?: WatchHandler) => new WatchVinylTransform({ source, handler });
-9
View File
@@ -75,17 +75,8 @@ export class Config {
this.flags = []; this.flags = [];
this.icon = null; this.icon = null;
this.meta = { this.meta = {
title: null,
filename: null,
icon: null,
version: null,
pack: null,
author: null,
company: null,
width: 800, width: 800,
height: 600, height: 600,
mobileWidth: null,
mobileHeight: null,
fps: 60, fps: 60,
}; };
this.key = null; this.key = null;
+1 -82
View File
@@ -1,89 +1,8 @@
import progress from "cli-progress";
import fs from "fs";
import fse from "fs-extra";
import got from "got";
import os from "os"; import os from "os";
import path from "path"; import path from "path";
import ps from "promise-streams"; import { Downloader } from "../common/download";
import tar from "tar";
import unzip from "unzip-stream";
import { Log } from "../common/log"; import { Log } from "../common/log";
export class Downloader {
static bar: progress.MultiBar;
static createProgressBar() {
if (Downloader.bar == null) {
Downloader.bar = new progress.MultiBar(
{
clearOnComplete: true,
},
progress.Presets.shades_grey,
);
}
return Downloader.bar.create();
}
static releaseProgressBar(bar: progress.MultiBar) {
bar.stop();
if (Downloader.bar != null) {
Downloader.bar.remove(bar);
if (Downloader.bar.bars.length === 0) {
Downloader.bar.stop();
Downloader.bar = null;
}
}
}
static download(url: string, dest: string, strip = 1, executable = false) {
fse.ensureDirSync(dest);
const bar = Downloader.createProgressBar();
let stream = got.stream(url);
stream = stream
.on("request", (r: any) => {
if (bar) bar.start(1, 0);
})
.on("downloadProgress", (p: any) => {
if (bar) {
bar.setTotal(p.total);
bar.update(p.transferred);
if (p.total === p.transferred) {
Downloader.releaseProgressBar(bar);
}
}
});
if (url.endsWith(".zip")) {
stream = stream.pipe(unzip.Parse()).on("entry", (entry: any) => {
const filePath = entry.path.split("/").slice(strip).join(path.sep);
if (filePath.length > 0) {
if (entry.type === "Directory") {
fse.ensureDirSync(path.join(dest, path.normalize(filePath)));
} else if (entry.type === "File") {
const fullFilePath = path.join(dest, path.normalize(filePath));
const dirPath = path.dirname(fullFilePath);
if (!fs.existsSync(dirPath)) {
fse.ensureDirSync(dirPath);
}
entry.pipe(
fs.createWriteStream(path.join(dest, path.normalize(filePath)), {
// ToDo: zip entry file mode?
mode: executable ? 0o755 : undefined,
}),
);
}
} else {
entry.autodrain();
}
});
} else if (url.endsWith("tar.gz")) {
stream = stream.pipe(tar.x({ C: dest, strip: strip }));
} else {
stream = stream.pipe(fs.createWriteStream(path.join(dest, url.split("/").pop()!)));
}
return ps.wait(stream);
}
}
export class Sdk { export class Sdk {
static _dir: string; static _dir: string;
+1
View File
@@ -1,3 +1,4 @@
// @ts-nocheck
import fs from "fs"; import fs from "fs";
import gulp from "gulp"; import gulp from "gulp";
import through from "through2"; import through from "through2";
+4 -3
View File
@@ -2,11 +2,12 @@ import fs from "fs";
import os from "os"; import os from "os";
import path from "path"; import path from "path";
import through from "through2"; import through from "through2";
import { Downloader } from "../common/download";
import { Env } from "../common/env"; import { Env } from "../common/env";
import exec from "../common/exec"; import exec from "../common/exec";
import { System } from "../common/system"; import { System } from "../common/system";
import { StringWritable } from "../common/tail"; import { HandlerWriter } from "../common/tail";
import { Downloader, Sdk } from "../core/sdk"; import { Sdk } from "../core/sdk";
import { Command } from "../run/command"; import { Command } from "../run/command";
export class Android extends Sdk { export class Android extends Sdk {
@@ -222,7 +223,7 @@ export class Android extends Sdk {
const command = new Command(cmd).exec(); const command = new Command(cmd).exec();
this.push(command); this.push(command);
command.contents.pipe( command.contents.pipe(
new StringWritable((line) => { new HandlerWriter((line: string) => {
if (line.includes("SDL") && (line.includes("onDestroy()") || line.includes("onStop()"))) { if (line.includes("SDL") && (line.includes("onDestroy()") || line.includes("onStop()"))) {
callback(); callback();
throw "Exit"; // ToDo: throw "Exit"; // ToDo:
+5 -18
View File
@@ -2,10 +2,9 @@ import fs from "fs";
import fse from "fs-extra"; import fse from "fs-extra";
import os from "os"; import os from "os";
import path from "path"; import path from "path";
import through from "through2";
import { Env } from "../common/env"; import { Env } from "../common/env";
import { System } from "../common/system"; import { System } from "../common/system";
import { TailVinyl } from "../common/tail"; import { watch } from "../common/watch";
import { Sdk } from "../core/sdk"; import { Sdk } from "../core/sdk";
import run from "../run"; import run from "../run";
@@ -60,7 +59,6 @@ export class FlashPlayer extends Sdk {
get flashPlayerBin(): string { get flashPlayerBin(): string {
if (System.isWindows) { if (System.isWindows) {
const v = this.version.split(".");
const playerName = `flashplayer_${this.version}_sa${this.debug ? "_debug" : ""}.exe`; const playerName = `flashplayer_${this.version}_sa${this.debug ? "_debug" : ""}.exe`;
return path.join(this.path, playerName); return path.join(this.path, playerName);
} else if (System.isLinux) { } else if (System.isLinux) {
@@ -74,7 +72,7 @@ export class FlashPlayer extends Sdk {
static get flashPlayerDir(): string { static get flashPlayerDir(): string {
if (os.type() === "Windows_NT") { if (os.type() === "Windows_NT") {
return path.join(process.env.APPDATA, "Macromedia", "Flash Player"); return path.join(process.env.APPDATA!, "Macromedia", "Flash Player");
} else if (os.type() === "Linux") { } else if (os.type() === "Linux") {
return path.join(os.homedir(), ".macromedia", "Flash_Player"); return path.join(os.homedir(), ".macromedia", "Flash_Player");
} else { } else {
@@ -90,7 +88,7 @@ export class FlashPlayer extends Sdk {
const filename = path.join(os.homedir(), "mm.cfg"); const filename = path.join(os.homedir(), "mm.cfg");
const value = "TraceOutputFileEnable=1"; const value = "TraceOutputFileEnable=1";
if (fs.existsSync(filename)) { if (fs.existsSync(filename)) {
const data = fs.readFileSync(filename); const data = fs.readFileSync(filename, "utf8");
if (data.indexOf(value) === -1) { if (data.indexOf(value) === -1) {
fs.appendFileSync(filename, `${value}\n`); fs.appendFileSync(filename, `${value}\n`);
} }
@@ -104,7 +102,7 @@ export class FlashPlayer extends Sdk {
static trust(value: string) { static trust(value: string) {
const filename = path.join(this.flashPlayerDir, "#Security", "FlashPlayerTrust", "gulp.cfg"); const filename = path.join(this.flashPlayerDir, "#Security", "FlashPlayerTrust", "gulp.cfg");
if (fs.existsSync(filename)) { if (fs.existsSync(filename)) {
const data = fs.readFileSync(filename); const data = fs.readFileSync(filename, "utf8");
if (data.indexOf(value) === -1) { if (data.indexOf(value) === -1) {
fs.appendFileSync(filename, `${value}\n`); fs.appendFileSync(filename, `${value}\n`);
} }
@@ -120,17 +118,6 @@ export class FlashPlayer extends Sdk {
this.log.i("_run_ *%s*", filename); this.log.i("_run_ *%s*", filename);
FlashPlayer.trust(filename); FlashPlayer.trust(filename);
FlashPlayer.enableLog(); FlashPlayer.enableLog();
return run(`${this.flashPlayerBin} ${filename}`, params) return run(`${this.flashPlayerBin} ${filename}`, params).exec().pipe(watch(FlashPlayer.log));
.exec()
.pipe(
through.obj(function (file: any, enc: string, callback: any) {
const log = new TailVinyl({
path: FlashPlayer.log,
});
this.on("end", () => log.dispose());
this.push(log);
callback();
}),
);
} }
} }
+13 -6
View File
@@ -77,7 +77,10 @@ export class Haxe extends Sdk {
prepare() { prepare() {
return Promise.all([this.neko.prepare(), super.prepare()]).then(() => { return Promise.all([this.neko.prepare(), super.prepare()]).then(() => {
fs.copyFileSync(path.resolve(import.meta.dirname, "..", "template/haxe/activate"), path.resolve(this.path, "activate")); fs.copyFileSync(
path.resolve(import.meta.dirname, "..", "template/haxe/activate"),
path.resolve(this.path, "activate"),
);
}); });
} }
@@ -112,7 +115,9 @@ export class Haxe extends Sdk {
const buildDir = this.resolveBuildDir(config); const buildDir = this.resolveBuildDir(config);
fse.ensureDirSync(buildDir); fse.ensureDirSync(buildDir);
const projectTemplate = template(fs.readFileSync(path.resolve(import.meta.dirname, "..", "template/project.xml"))); const projectTemplate = template(
fs.readFileSync(path.resolve(import.meta.dirname, "..", "template/project.xml"), "utf8"),
);
const project = projectTemplate({ ...config, buildDir: buildDir }); const project = projectTemplate({ ...config, buildDir: buildDir });
fs.writeFileSync(path.resolve(buildDir, "project.xml"), project); fs.writeFileSync(path.resolve(buildDir, "project.xml"), project);
@@ -128,7 +133,7 @@ export class Haxe extends Sdk {
flash: "*.swf", flash: "*.swf",
}[platform] || "**/*"; }[platform] || "**/*";
return this.haxelib(args).then(() => { return this.haxelib(args).then(() => {
let r = vfs.src(`${target}/${result}`); let r = vfs.src(`${target}/${result}`, { encoding: false });
if (platform === "android") { if (platform === "android") {
r = r.pipe(rename(`${config.meta.filename}_${config.meta.version}.apk`)); r = r.pipe(rename(`${config.meta.filename}_${config.meta.version}.apk`));
} }
@@ -142,7 +147,9 @@ export class Haxe extends Sdk {
const buildDir = this.resolveBuildDir(config); const buildDir = this.resolveBuildDir(config);
fse.ensureDirSync(buildDir); fse.ensureDirSync(buildDir);
const projectTemplate = template(fs.readFileSync(path.resolve(import.meta.dirname, "..", "template/project.hxml"))); const projectTemplate = template(
fs.readFileSync(path.resolve(import.meta.dirname, "..", "template/project.hxml"), "utf8"),
);
const ext = const ext =
{ {
@@ -175,9 +182,9 @@ export class Haxe extends Sdk {
cpp: `${config.meta.filename}/${config.main.split(".").pop()}${debug ? "-debug" : ""}`, cpp: `${config.meta.filename}/${config.main.split(".").pop()}${debug ? "-debug" : ""}`,
}[platform] || "**/*"; }[platform] || "**/*";
return this.haxe(args).then(() => { return this.haxe(args).then(() => {
let r = vfs.src(`${target}/${result}`); let r = vfs.src(`${target}/${result}`, { encoding: false });
if (platform === "cpp") { if (platform === "cpp") {
r = r.pipe(rename(config.meta.filename)); r = r.pipe(rename(config.meta.filename!));
} }
return r; return r;
}); });
+3 -1
View File
@@ -43,7 +43,9 @@ export class InnoSetup extends Sdk {
pack(config: Config, source: string, output: string) { pack(config: Config, source: string, output: string) {
const buildDir = path.join(os.tmpdir(), "build", config.name, "innosetup"); const buildDir = path.join(os.tmpdir(), "build", config.name, "innosetup");
const appTemplate = template(fs.readFileSync(path.resolve(import.meta.dirname, "..", "template/windows/app.iss"), "utf8")); const appTemplate = template(
fs.readFileSync(path.resolve(import.meta.dirname, "..", "template/windows/app.iss"), "utf8"),
);
const app = appTemplate({ ...config, buildDir: buildDir, output: output }); const app = appTemplate({ ...config, buildDir: buildDir, output: output });
fse.ensureDirSync(buildDir); fse.ensureDirSync(buildDir);
+9 -13
View File
@@ -1,9 +1,8 @@
import os from "os"; import os from "os";
import path from "path"; import path from "path";
import through from "through2";
import { Env } from "../common/env"; import { Env } from "../common/env";
import { System } from "../common/system"; import { System } from "../common/system";
import { TailVinyl } from "../common/tail"; import { watch } from "../common/watch";
import run from "../run"; import run from "../run";
import { FlashPlayer } from "./flashplayer"; import { FlashPlayer } from "./flashplayer";
@@ -11,7 +10,11 @@ export class RufflePlayer extends FlashPlayer {
static ID = "ruffle"; static ID = "ruffle";
static VERSION_2026_05_15 = "nightly-2026_05_15"; static VERSION_2026_05_15 = "nightly-2026_05_15";
static VERSION = RufflePlayer.VERSION_2026_05_15; static VERSION_2026_10_13 = "nightly-2026_10_13";
static VERSION_0_5_0 = "0.5.0";
static VERSION_0_6_0 = "0.6.0";
static VERSION_0_7_1 = "0.7.1";
static VERSION = RufflePlayer.VERSION_2026_10_13;
BASE_URL = "https://github.com/ruffle-rs/ruffle/releases/download"; BASE_URL = "https://github.com/ruffle-rs/ruffle/releases/download";
@@ -21,7 +24,8 @@ export class RufflePlayer extends FlashPlayer {
} }
get link(): string { get link(): string {
const baseUrl = `${this.baseUrl}/${this.version.replaceAll("_", "-")}`; const nightly = this.version.includes("nightly");
const baseUrl = `${this.baseUrl}/${nightly ? "" : "v"}${this.version.replaceAll("_", "-")}`;
if (System.isWindows) { if (System.isWindows) {
return baseUrl + `/ruffle-${this.version}-windows-x86_64.zip`; return baseUrl + `/ruffle-${this.version}-windows-x86_64.zip`;
} else if (System.isLinux) { } else if (System.isLinux) {
@@ -50,18 +54,10 @@ export class RufflePlayer extends FlashPlayer {
return run(`${this.flashPlayerBin} ${filename}`, params) return run(`${this.flashPlayerBin} ${filename}`, params)
.exec() .exec()
.pipe( .pipe(
through.obj(function (file: any, enc: string, callback: any) { watch(RufflePlayer.log, (line: string) => {
const log = new TailVinyl({
path: RufflePlayer.log,
handler: (line: string) => {
if (line.includes("avm_trace")) { if (line.includes("avm_trace")) {
return line.split("avm_trace: ").pop(); return line.split("avm_trace: ").pop();
} }
},
});
this.on("end", () => log.dispose());
this.push(log);
callback();
}), }),
); );
} }
+3
View File
@@ -1,5 +1,6 @@
export * from "./common/system"; export * from "./common/system";
export * from "./core/config"; export * from "./core/config";
export * from "./common/download";
export * from "./core/sdk"; export * from "./core/sdk";
export * from "./core/type"; export * from "./core/type";
export * from "./impl/android"; export * from "./impl/android";
@@ -9,3 +10,5 @@ export * from "./impl/innosetup";
export * from "./impl/neko"; export * from "./impl/neko";
export * from "./impl/ruffle"; export * from "./impl/ruffle";
export * from "./project"; export * from "./project";
export * from "./project/impl";
export * from "./project/preset";
-524
View File
@@ -1,524 +0,0 @@
import fs from "fs";
import fse from "fs-extra";
import gulp from "gulp";
import deb from "gulp-debian";
import gzip from "gulp-gzip";
import rename from "gulp-rename";
import tar from "gulp-tar";
import webserver from "gulp-webserver";
import zip from "gulp-zip";
import template from "lodash.template";
import os from "os";
import path from "path";
import vfs from "vinyl-fs";
import { DEBUG } from "./common/debug";
import exec from "./common/exec";
import { tail } from "./common/tail";
import { Config } from "./core/config";
import { BuildSystem, Platform } from "./core/type";
import { Android } from "./impl/android";
import { FlashPlayer } from "./impl/flashplayer";
import { Haxe } from "./impl/haxe";
import { InnoSetup } from "./impl/innosetup";
import { Neko } from "./impl/neko";
import { RufflePlayer } from "./impl/ruffle";
import run from "./run";
const streamToPromise = (stream: any) => {
return new Promise((resolve, reject) => {
stream.on("end", resolve);
stream.on("error", reject);
});
};
export class Target {
public config: Config;
public platform: string;
public target: string;
constructor(config: Config, platform: string) {
this.config = config;
this.platform = platform;
this.target = "target";
}
prepare(): Promise<any> {
return Promise.resolve();
}
call() {
throw "Not Implemented";
}
resolveTargetPath(platform = this.platform): string {
return path.resolve(this.target, this.config.name, platform);
}
get targetPath(): string {
return this.resolveTargetPath();
}
}
export class Builder extends Target {
static factory: Record<string, typeof Builder> = {};
public buildSystem: string;
public debug: boolean;
constructor(config: Config, platform: string, buildSystem: string, debug: boolean = false) {
super(config, platform);
this.buildSystem = buildSystem;
this.debug = debug;
}
static register(buildSystem: string, builder: typeof Builder) {
Builder.factory[buildSystem] = builder;
}
static new(config: Config, platform: string, buildSystem: string, debug: boolean = false): Builder {
return new Builder.factory[buildSystem](config, platform, buildSystem, debug);
}
}
export class HaxeBuilder extends Builder {
public haxe: Haxe;
public android: Android;
constructor(config: Config, platform: string, buildSystem: string, debug: boolean = false) {
super(config, platform, buildSystem, debug);
this.haxe = new Haxe();
this.android = new Android();
}
prepare() {
let result = this.haxe.prepare().then(() => this.haxe.install(this.config.libs));
if (this.buildSystem === BuildSystem.OPENFL) {
if (this.platform === Platform.ANDROID) {
result = result
.then(() => this.android.prepare())
.then(() => this.android.activate())
.then(() =>
this.android.sdkmanager([
// ToDo: android sdk dependencies config?
//'tools',
"platform-tools",
"build-tools;27.0.3",
"platforms;android-28", //ToDo: lime version 7.6.0 -> 28; 7.0.0 -> 26
//'ndk-bundle',
//'lldb;3.1',
"cmake;3.6.4111459",
]),
);
const AndroidSDK = this.android.android_home;
const AndroidNDK = this.android.ndk_home;
const answer = `echo "${[AndroidSDK, AndroidNDK].join("\n")}"`;
result = result.then(() => {
return exec(".", [answer, "|", this.haxe.haxelibBin, "run", "openfl", "setup", this.platform].join(" "));
});
}
}
return result;
}
call() {
const target = this.targetPath;
switch (this.buildSystem) {
case BuildSystem.OPENFL:
return this.haxe.openfl("build", this.platform, this.config, this.debug).then((result) => {
if (this.platform === Platform.ANDROID && this.config.key) {
result = result.pipe(this.android.sign(this.config.key.store, this.config.key.pass));
}
return streamToPromise(result.pipe(vfs.dest(target)));
});
case BuildSystem.HAXE:
return this.haxe
.build(this.platform, this.config, this.debug)
.then((result) => streamToPromise(result.pipe(vfs.dest(target))));
}
}
}
Builder.register(BuildSystem.HAXE, HaxeBuilder);
Builder.register(BuildSystem.OPENFL, HaxeBuilder);
export type PackerFactoty = new (config: Config) => Packer;
export class Packer extends Target {
static factory: Record<string, Record<string, PackerFactoty>> = {};
call() {
throw "Not Implemented";
}
static register(platform: string, name: string, packer: PackerFactoty) {
if (!Packer.factory[platform]) Packer.factory[platform] = {};
Packer.factory[platform][name] = packer;
}
static new(config: Config, platform: string, name: string): Packer {
return new Packer.factory[platform][name](config);
}
}
export class FlashHTMLPacker extends Packer {
static NAME = "html";
constructor(config: Config) {
super(config, Platform.FLASH);
}
call() {
const target = this.targetPath;
const indexTemplate = template(
fs.readFileSync(path.resolve(import.meta.dirname, "..", "template/flash/index.html")),
);
const index = indexTemplate(this.config);
fs.writeFileSync(path.resolve(target, "index.html"), index);
fs.copyFileSync(path.resolve(import.meta.dirname, "..", "template/flash/swf.js"), path.resolve(target, "swf.js"));
return Promise.resolve();
}
}
Packer.register(Platform.FLASH, FlashHTMLPacker.NAME, FlashHTMLPacker);
export class LinuxDEBPacker extends Packer {
static NAME = "deb";
constructor(config: Config) {
super(config, Platform.LINUX);
}
call() {
const target = this.targetPath;
const buildDir = path.join(os.tmpdir(), "build", this.config.name, "debian");
const iconfile = `${this.config.meta.filename}${path.extname(this.config.meta.icon!)}`;
const desktopTemplate = template(
fs.readFileSync(path.resolve(import.meta.dirname, "..", "template/linux/app.desktop")),
);
const desktop = desktopTemplate(Object.assign({ iconfile: iconfile }, this.config));
fse.ensureDirSync(`${buildDir}/usr/share/applications`);
fs.writeFileSync(`${buildDir}/usr/share/applications/${this.config.meta.filename}.desktop`, desktop);
fse.copySync(`${target}`, `${buildDir}/usr/share/${this.config.meta.filename}/`);
fse.copySync(this.config.meta.icon!, `${buildDir}/usr/share/${this.config.meta.filename}/${iconfile}`);
return gulp.src(`${buildDir}/*`).pipe(
deb({
package: this.config.meta.filename,
version: this.config.meta.version,
section: "base",
priority: "optional",
architecture: "all",
maintainer: this.config.meta.author,
description: this.config.meta.title,
changelog: [],
postinst: [
'if [ "$1" = "configure" ] && [ -x "`which update-menus 2>/dev/null`" ] ; then\n' +
" update-menus\n" +
"fi",
],
_target: "/",
_out: this.resolveTargetPath("debian"),
_clean: true,
_verbose: false,
}),
);
}
}
Packer.register(Platform.LINUX, LinuxDEBPacker.NAME, LinuxDEBPacker);
export class LinuxArchivePacker extends Packer {
static NAME = "archive";
constructor(config: Config) {
super(config, Platform.LINUX);
}
call() {
const target = this.targetPath;
const archiveName = `${this.config.meta.filename}_${this.config.meta.version}_linux.tar`;
return gulp
.src(`${target}/**/*`)
.pipe(tar(archiveName))
.pipe(gzip())
.pipe(gulp.dest(this.resolveTargetPath("archive")));
}
}
Packer.register(Platform.LINUX, LinuxArchivePacker.NAME, LinuxArchivePacker);
export class WindowsInstallerPacker extends Packer {
static NAME = "installer";
public innosetup: InnoSetup;
constructor(config: Config) {
super(config, Platform.WINDOWS);
this.innosetup = new InnoSetup();
}
prepare() {
return this.innosetup.prepare();
}
call() {
return this.innosetup.pack(this.config, this.targetPath, this.resolveTargetPath("installer"));
}
}
Packer.register(Platform.WINDOWS, WindowsInstallerPacker.NAME, WindowsInstallerPacker);
export class WindowsArchivePacker extends Packer {
static NAME = "archive";
constructor(config: Config) {
super(config, Platform.WINDOWS);
}
call() {
const target = this.targetPath;
const archiveName = `${this.config.meta.filename}_${this.config.meta.version}_win.zip`;
return gulp
.src(`${target}/**/*`)
.pipe(zip(archiveName))
.pipe(gulp.dest(this.resolveTargetPath("archive")));
}
}
Packer.register(Platform.WINDOWS, WindowsArchivePacker.NAME, WindowsArchivePacker);
export type RunnerFactory = new (config: Config, debug: boolean) => Runner;
export class Runner extends Target {
static factory: Record<string, RunnerFactory> = {};
public debug: boolean;
constructor(config: Config, platform: string, debug: boolean) {
super(config, platform);
this.debug = debug;
}
log(stream: any) {
return stream.pipe(tail(DEBUG.log)).pipe(rename("out.log")).pipe(gulp.dest(this.targetPath));
}
static register(platform: string, runner: RunnerFactory) {
Runner.factory[platform] = runner;
}
static new(config: Config, platform: string, debug: boolean): Runner {
return new Runner.factory[platform](config, debug);
}
}
export class FlashRunner extends Runner {
public player: FlashPlayer;
constructor(config: Config, debug: boolean, player: typeof FlashPlayer = FlashPlayer) {
super(config, Platform.FLASH, debug);
this.player = new player(debug);
}
prepare() {
return this.player.prepare();
}
call() {
const target = this.targetPath;
const filename = path.resolve(target, this.config.meta.filename + ".swf");
const result = this.player.run(filename, { cwd: target, verbosity: 0 });
return this.log(result);
}
}
class RuffleRunner extends FlashRunner {
constructor(config: Config, debug: boolean) {
super(config, debug, RufflePlayer);
}
}
Runner.register(Platform.FLASH, FlashRunner);
export class Html5Runner extends Runner {
constructor(config: Config, debug: boolean) {
super(config, Platform.HTML5, debug);
}
call() {
return gulp.src(this.targetPath).pipe(
webserver({
// ToDo: config?
host: "0.0.0.0",
port: 3000,
open: true,
fallback: "index.html",
}),
);
}
}
Runner.register(Platform.HTML5, Html5Runner);
export class LinuxRunner extends Runner {
constructor(config: Config, debug: boolean) {
super(config, Platform.LINUX, debug);
}
call() {
const target = this.targetPath;
const filename = path.resolve(target, this.config.meta.filename!);
const result = gulp.src(filename).pipe(run("./<%=file.basename%>", { cwd: target, verbosity: 0 }));
return this.log(result);
}
}
Runner.register(Platform.LINUX, LinuxRunner);
export class CPPRunner extends LinuxRunner {
constructor(config: Config, debug: boolean) {
super(config, debug);
this.platform = Platform.CPP;
}
}
Runner.register(Platform.CPP, CPPRunner);
export class WindowsRunner extends Runner {
constructor(config: Config, debug: boolean) {
super(config, Platform.WINDOWS, debug);
}
call() {
const target = this.targetPath;
const filename = path.resolve(target, this.config.meta.filename + ".exe");
const result = gulp.src(filename).pipe(run("<%=file.basename%>", { cwd: target, verbosity: 0 }));
return this.log(result);
}
}
Runner.register(Platform.WINDOWS, WindowsRunner);
export class NekoRunner extends Runner {
protected neko: Neko;
constructor(config: Config, debug: boolean) {
super(config, Platform.NEKO, debug);
this.neko = new Neko();
}
prepare() {
return this.neko.prepare();
}
call() {
const target = this.targetPath;
const filename = path.resolve(target, this.config.meta.filename + ".n");
const result = this.neko.run(filename, { cwd: target, verbosity: 0 });
return this.log(result);
}
}
Runner.register(Platform.NEKO, NekoRunner);
/**
*
*/
export class AndroidRunner extends Runner {
protected android: Android;
constructor(config: Config, debug: boolean) {
super(config, Platform.ANDROID, debug);
this.android = new Android();
}
prepare() {
return this.android.prepare();
}
call() {
const target = this.targetPath;
return this.log(
gulp
.src(`${target}/${this.config.meta.filename}_${this.config.meta.version}.apk`)
.pipe(this.android.apk())
.pipe(this.android.install())
.pipe(this.android.start())
.pipe(this.android.logcat()),
);
}
}
Runner.register(Platform.ANDROID, AndroidRunner);
export type Task = any; // TODO: gulp task type
export class Project {
// TODO: compatibility
static Config = Config;
static BuildSystem = BuildSystem;
static Platform = Platform;
static Builder = Builder;
public buildSystem: string;
public platforms: string[];
public config: Config;
public prepare: (() => Task) | null;
constructor(buildSystem: string, platforms: string[] | string, config: Config, prepare: (() => Task) | null = null) {
this.buildSystem = buildSystem;
this.platforms = Array.isArray(platforms) ? platforms : [platforms];
this.config = config;
this.prepare = prepare;
}
build(platform: string, debug: boolean = false): Task[] {
const builder = Builder.new(this.config, platform, this.buildSystem, debug);
const tasks: Task[] = [builder.prepare.bind(builder)];
if (this.prepare) tasks.push(this.prepare);
tasks.push(builder.call.bind(builder));
return tasks;
}
run(platform: string, debug: boolean = false): Task[] {
const runner = Runner.new(this.config, platform, debug);
return [runner.prepare.bind(runner), runner.call.bind(runner)];
}
test(platform: string, debug: boolean = true): Task[] {
return this.build(platform, debug).concat(this.run(platform, debug));
}
pack(platform: string, name: string) {
const packer = Packer.new(this.config, platform, name);
return [packer.prepare.bind(packer), packer.call.bind(packer)];
}
compile(external_gulp?: any): Record<string, Task> {
const result: Record<string, Task> = {};
const _gulp = external_gulp || gulp;
for (const platform of this.platforms) {
result[`${this.config.name}:${platform}:build`] = _gulp.series(this.build(platform));
if (Runner.factory[platform]) {
result[`${this.config.name}:${platform}:run`] = _gulp.series(this.run(platform));
result[`${this.config.name}:${platform}:test`] = _gulp.series(this.test(platform));
}
if (Packer.factory[platform]) {
for (const name of Object.keys(Packer.factory[platform])) {
result[`${this.config.name}:${platform}:${name}`] = _gulp.series(this.pack(platform, name));
}
}
}
return result;
}
register(external_gulp?: any) {
const _gulp = external_gulp || gulp;
for (const [k, v] of Object.entries(this.compile(_gulp))) {
_gulp.task(k, v);
}
}
static useRuffle() {
Runner.register(Platform.FLASH, RuffleRunner);
}
}
+23
View File
@@ -0,0 +1,23 @@
import type { Config } from "../../core/config";
import { Target } from "./target";
export class Builder extends Target {
static factory: Record<string, typeof Builder> = {};
public buildSystem: string;
public debug: boolean;
constructor(config: Config, platform: string, buildSystem: string, debug: boolean = false) {
super(config, platform);
this.buildSystem = buildSystem;
this.debug = debug;
}
static register(buildSystem: string, builder: typeof Builder) {
Builder.factory[buildSystem] = builder;
}
static new(config: Config, platform: string, buildSystem: string, debug: boolean = false): Builder {
return new Builder.factory[buildSystem](config, platform, buildSystem, debug);
}
}
+4
View File
@@ -0,0 +1,4 @@
export * from "./builder";
export * from "./packer";
export * from "./runner";
export * from "./target";
+21
View File
@@ -0,0 +1,21 @@
import type { Config } from "../../core/config";
import { Target } from "./target";
export type PackerFactory = new (config: Config) => Packer;
export class Packer extends Target {
static factory: Record<string, Record<string, PackerFactory>> = {};
call() {
throw "Not Implemented";
}
static register(platform: string, name: string, packer: PackerFactory) {
if (!Packer.factory[platform]) Packer.factory[platform] = {};
Packer.factory[platform][name] = packer;
}
static new(config: Config, platform: string, name: string): Packer {
return new Packer.factory[platform][name](config);
}
}
+31
View File
@@ -0,0 +1,31 @@
import gulp from "gulp";
import rename from "gulp-rename";
import { DEBUG } from "../../common/debug";
import { tail } from "../../common/tail";
import { Config } from "../../core/config";
import { Target } from "./target";
export type RunnerFactory = new (config: Config, debug: boolean) => Runner;
export class Runner extends Target {
static factory: Record<string, RunnerFactory> = {};
public debug: boolean;
constructor(config: Config, platform: string, debug: boolean) {
super(config, platform);
this.debug = debug;
}
log(stream: any) {
return stream.pipe(tail(DEBUG.log)).pipe(rename("out.log")).pipe(gulp.dest(this.targetPath));
}
static register(platform: string, runner: RunnerFactory) {
Runner.factory[platform] = runner;
}
static new(config: Config, platform: string, debug: boolean): Runner {
return new Runner.factory[platform](config, debug);
}
}
+30
View File
@@ -0,0 +1,30 @@
import path from "path";
import type { Config } from "../../core/config";
export class Target {
public config: Config;
public platform: string;
public target: string;
constructor(config: Config, platform: string) {
this.config = config;
this.platform = platform;
this.target = "target";
}
prepare(): Promise<any> {
return Promise.resolve();
}
call() {
throw "Not Implemented";
}
resolveTargetPath(platform = this.platform): string {
return path.resolve(this.target, this.config.name, platform);
}
get targetPath(): string {
return this.resolveTargetPath();
}
}
+69
View File
@@ -0,0 +1,69 @@
import vfs from "vinyl-fs";
import exec from "../../../common/exec";
import { streamToPromise } from "../../../common/util";
import { Config } from "../../../core/config";
import { BuildSystem, Platform } from "../../../core/type";
import { Android } from "../../../impl/android";
import { Haxe } from "../../../impl/haxe";
import { Builder } from "../../core/builder";
export class HaxeBuilder extends Builder {
public haxe: Haxe;
public android: Android;
constructor(config: Config, platform: string, buildSystem: string, debug: boolean = false) {
super(config, platform, buildSystem, debug);
this.haxe = new Haxe();
this.android = new Android();
}
prepare() {
let result = this.haxe.prepare().then(() => this.haxe.install(this.config.libs));
if (this.buildSystem === BuildSystem.OPENFL) {
if (this.platform === Platform.ANDROID) {
result = result
.then(() => this.android.prepare())
.then(() => this.android.activate())
.then(() =>
this.android.sdkmanager([
// ToDo: android sdk dependencies config?
//'tools',
"platform-tools",
"build-tools;27.0.3",
"platforms;android-28", //ToDo: lime version 7.6.0 -> 28; 7.0.0 -> 26
//'ndk-bundle',
//'lldb;3.1',
"cmake;3.6.4111459",
]),
);
const AndroidSDK = this.android.android_home;
const AndroidNDK = this.android.ndk_home;
const answer = `echo "${[AndroidSDK, AndroidNDK].join("\n")}"`;
result = result.then(() => {
return exec(".", [answer, "|", this.haxe.haxelibBin, "run", "openfl", "setup", this.platform].join(" "));
});
}
}
return result;
}
call() {
const target = this.targetPath;
switch (this.buildSystem) {
case BuildSystem.OPENFL:
return this.haxe.openfl("build", this.platform, this.config, this.debug).then((result) => {
if (this.platform === Platform.ANDROID && this.config.key) {
result = result.pipe(this.android.sign(this.config.key.store, this.config.key.pass));
}
return streamToPromise(result.pipe(vfs.dest(target)));
});
case BuildSystem.HAXE:
return this.haxe
.build(this.platform, this.config, this.debug)
.then((result) => streamToPromise(result.pipe(vfs.dest(target))));
}
}
}
Builder.register(BuildSystem.HAXE, HaxeBuilder);
Builder.register(BuildSystem.OPENFL, HaxeBuilder);
+13
View File
@@ -0,0 +1,13 @@
export * from "./builder/haxe";
export * from "./packer/flash";
export * from "./packer/linux/archive";
export * from "./packer/linux/deb";
export * from "./packer/windows/archive";
export * from "./packer/windows/installer";
export * from "./runner/android";
export * from "./runner/flash";
export * from "./runner/html5";
export * from "./runner/linux";
export * from "./runner/neko";
export * from "./runner/ruffle";
export * from "./runner/windows";
+27
View File
@@ -0,0 +1,27 @@
import fs from "fs";
import template from "lodash.template";
import path from "path";
import type { Config } from "../../../core/config";
import { Platform } from "../../../core/type";
import { Packer } from "../../core/packer";
export class FlashHTMLPacker extends Packer {
static NAME = "html";
constructor(config: Config) {
super(config, Platform.FLASH);
}
call() {
const target = this.targetPath;
const indexTemplate = template(
fs.readFileSync(path.resolve(import.meta.dirname, "..", "template/flash/index.html"), "utf8"),
);
const index = indexTemplate(this.config);
fs.writeFileSync(path.resolve(target, "index.html"), index);
fs.copyFileSync(path.resolve(import.meta.dirname, "..", "template/flash/swf.js"), path.resolve(target, "swf.js"));
return Promise.resolve();
}
}
Packer.register(Platform.FLASH, FlashHTMLPacker.NAME, FlashHTMLPacker);
+26
View File
@@ -0,0 +1,26 @@
import gulp from "gulp";
import gzip from "gulp-gzip";
import tar from "gulp-tar";
import type { Config } from "../../../../core/config";
import { Platform } from "../../../../core/type";
import { Packer } from "../../../core/packer";
export class LinuxArchivePacker extends Packer {
static NAME = "archive";
constructor(config: Config) {
super(config, Platform.LINUX);
}
call() {
const target = this.targetPath;
const archiveName = `${this.config.meta.filename}_${this.config.meta.version}_linux.tar`;
return gulp
.src(`${target}/**/*`)
.pipe(tar(archiveName))
.pipe(gzip())
.pipe(gulp.dest(this.resolveTargetPath("archive")));
}
}
Packer.register(Platform.LINUX, LinuxArchivePacker.NAME, LinuxArchivePacker);
+55
View File
@@ -0,0 +1,55 @@
import fs from "fs";
import fse from "fs-extra";
import gulp from "gulp";
import deb from "gulp-debian";
import { template } from "lodash";
import os from "os";
import path from "path";
import { Config } from "../../../../core/config";
import { Platform } from "../../../../core/type";
import { Packer } from "../../../core/packer";
export class LinuxDEBPacker extends Packer {
static NAME = "deb";
constructor(config: Config) {
super(config, Platform.LINUX);
}
call() {
const target = this.targetPath;
const buildDir = path.join(os.tmpdir(), "build", this.config.name, "debian");
const iconfile = `${this.config.meta.filename}${path.extname(this.config.meta.icon!)}`;
const desktopTemplate = template(
fs.readFileSync(path.resolve(import.meta.dirname, "..", "template/linux/app.desktop"), "utf8"),
);
const desktop = desktopTemplate(Object.assign({ iconfile: iconfile }, this.config));
fse.ensureDirSync(`${buildDir}/usr/share/applications`);
fs.writeFileSync(`${buildDir}/usr/share/applications/${this.config.meta.filename}.desktop`, desktop);
fse.copySync(`${target}`, `${buildDir}/usr/share/${this.config.meta.filename}/`);
fse.copySync(this.config.meta.icon!, `${buildDir}/usr/share/${this.config.meta.filename}/${iconfile}`);
return gulp.src(`${buildDir}/*`).pipe(
deb({
package: this.config.meta.filename!,
version: this.config.meta.version!,
section: "base",
priority: "optional",
architecture: "all",
maintainer: this.config.meta.author,
description: this.config.meta.title,
changelog: [],
postinst: [
'if [ "$1" = "configure" ] && [ -x "`which update-menus 2>/dev/null`" ] ; then\n' +
" update-menus\n" +
"fi",
],
_target: "/",
_out: this.resolveTargetPath("debian"),
_clean: true,
_verbose: false,
}),
);
}
}
Packer.register(Platform.LINUX, LinuxDEBPacker.NAME, LinuxDEBPacker);
@@ -0,0 +1,24 @@
import gulp from "gulp";
import zip from "gulp-zip";
import { Config } from "../../../../core/config";
import { Platform } from "../../../../core/type";
import { Packer } from "../../../core/packer";
export class WindowsArchivePacker extends Packer {
static NAME = "archive";
constructor(config: Config) {
super(config, Platform.WINDOWS);
}
call() {
const target = this.targetPath;
const archiveName = `${this.config.meta.filename}_${this.config.meta.version}_win.zip`;
return gulp
.src(`${target}/**/*`)
.pipe(zip(archiveName))
.pipe(gulp.dest(this.resolveTargetPath("archive")));
}
}
Packer.register(Platform.WINDOWS, WindowsArchivePacker.NAME, WindowsArchivePacker);
@@ -0,0 +1,25 @@
import { Config } from "../../../../core/config";
import { Platform } from "../../../../core/type";
import { InnoSetup } from "../../../../impl/innosetup";
import { Packer } from "../../../core/packer";
export class WindowsInstallerPacker extends Packer {
static NAME = "installer";
public innosetup: InnoSetup;
constructor(config: Config) {
super(config, Platform.WINDOWS);
this.innosetup = new InnoSetup();
}
prepare() {
return this.innosetup.prepare();
}
call() {
return this.innosetup.pack(this.config, this.targetPath, this.resolveTargetPath("installer"));
}
}
Packer.register(Platform.WINDOWS, WindowsInstallerPacker.NAME, WindowsInstallerPacker);
+32
View File
@@ -0,0 +1,32 @@
import gulp from "gulp";
import type { Config } from "../../../core/config";
import { Platform } from "../../../core/type";
import { Android } from "../../../impl/android";
import { Runner } from "../../core/runner";
export class AndroidRunner extends Runner {
protected android: Android;
constructor(config: Config, debug: boolean) {
super(config, Platform.ANDROID, debug);
this.android = new Android();
}
prepare() {
return this.android.prepare();
}
call() {
const target = this.targetPath;
return this.log(
gulp
.src(`${target}/${this.config.meta.filename}_${this.config.meta.version}.apk`)
.pipe(this.android.apk())
.pipe(this.android.install())
.pipe(this.android.start())
.pipe(this.android.logcat()),
);
}
}
Runner.register(Platform.ANDROID, AndroidRunner);
+27
View File
@@ -0,0 +1,27 @@
import path from "path";
import { Config } from "../../../core/config";
import { Platform } from "../../../core/type";
import { FlashPlayer } from "../../../impl/flashplayer";
import { Runner } from "../../core/runner";
export class FlashRunner extends Runner {
public player: FlashPlayer;
constructor(config: Config, debug: boolean, player: typeof FlashPlayer = FlashPlayer) {
super(config, Platform.FLASH, debug);
this.player = new player(debug);
}
prepare() {
return this.player.prepare();
}
call() {
const target = this.targetPath;
const filename = path.resolve(target, this.config.meta.filename + ".swf");
const result = this.player.run(filename, { cwd: target, verbosity: 0 });
return this.log(result);
}
}
Runner.register(Platform.FLASH, FlashRunner);
+21
View File
@@ -0,0 +1,21 @@
import connect from "gulp-connect";
import { Config } from "../../../core/config";
import { Platform } from "../../../core/type";
import { Runner } from "../../core/runner";
export class Html5Runner extends Runner {
constructor(config: Config, debug: boolean) {
super(config, Platform.HTML5, debug);
}
call() {
return connect.server({
root: this.targetPath,
host: "0.0.0.0",
port: 3000,
fallback: "index.html",
});
}
}
Runner.register(Platform.HTML5, Html5Runner);
+30
View File
@@ -0,0 +1,30 @@
import gulp from "gulp";
import path from "path";
import { Config } from "../../../core/config";
import { Platform } from "../../../core/type";
import run from "../../../run";
import { Runner } from "../../core/runner";
export class LinuxRunner extends Runner {
constructor(config: Config, debug: boolean) {
super(config, Platform.LINUX, debug);
}
call() {
const target = this.targetPath;
const filename = path.resolve(target, this.config.meta.filename!);
const result = gulp.src(filename).pipe(run("./<%=file.basename%>", { cwd: target, verbosity: 0 }));
return this.log(result);
}
}
Runner.register(Platform.LINUX, LinuxRunner);
export class CPPRunner extends LinuxRunner {
constructor(config: Config, debug: boolean) {
super(config, debug);
this.platform = Platform.CPP;
}
}
Runner.register(Platform.CPP, CPPRunner);
+27
View File
@@ -0,0 +1,27 @@
import path from "path";
import { Config } from "../../../core/config";
import { Platform } from "../../../core/type";
import { Neko } from "../../../impl/neko";
import { Runner } from "../../core/runner";
export class NekoRunner extends Runner {
public neko: Neko;
constructor(config: Config, debug: boolean) {
super(config, Platform.NEKO, debug);
this.neko = new Neko();
}
prepare() {
return this.neko.prepare();
}
call() {
const target = this.targetPath;
const filename = path.resolve(target, this.config.meta.filename + ".n");
const result = this.neko.run(filename, { cwd: target, verbosity: 0 });
return this.log(result);
}
}
Runner.register(Platform.NEKO, NekoRunner);
+9
View File
@@ -0,0 +1,9 @@
import type { Config } from "../../../core/config";
import { RufflePlayer } from "../../../impl/ruffle";
import { FlashRunner } from "./flash";
export class RuffleRunner extends FlashRunner {
constructor(config: Config, debug: boolean) {
super(config, debug, RufflePlayer);
}
}
+21
View File
@@ -0,0 +1,21 @@
import gulp from "gulp";
import path from "path";
import { Config } from "../../../core/config";
import { Platform } from "../../../core/type";
import run from "../../../run";
import { Runner } from "../../core/runner";
export class WindowsRunner extends Runner {
constructor(config: Config, debug: boolean) {
super(config, Platform.WINDOWS, debug);
}
call() {
const target = this.targetPath;
const filename = path.resolve(target, this.config.meta.filename + ".exe");
const result = gulp.src(filename).pipe(run("<%=file.basename%>", { cwd: target, verbosity: 0 }));
return this.log(result);
}
}
Runner.register(Platform.WINDOWS, WindowsRunner);
+87
View File
@@ -0,0 +1,87 @@
import gulp from "gulp";
import type { Task, TaskFunction } from "undertaker";
import { Config } from "../core/config";
import { BuildSystem, Platform } from "../core/type";
import { Builder } from "./core/builder";
import { Packer } from "./core/packer";
import { Runner } from "./core/runner";
import { RuffleRunner } from "./impl/runner/ruffle";
export * from "./core";
export class Project {
// TODO: compatibility
static Config = Config;
static BuildSystem = BuildSystem;
static Platform = Platform;
static Builder = Builder;
public buildSystem: string;
public platforms: string[];
public config: Config;
constructor(buildSystem: string, platforms: string[] | string, config: Config) {
this.buildSystem = buildSystem;
this.platforms = Array.isArray(platforms) ? platforms : [platforms];
this.config = config;
}
hasLib(name: string): boolean {
for (const lib of this.config.libs) {
if (lib.name === name) {
return true;
}
}
return false;
}
build(platform: string, debug: boolean = false): Task[] {
const builder = Builder.new(this.config, platform, this.buildSystem, debug);
const tasks: Task[] = [builder.prepare.bind(builder)];
tasks.push(builder.call.bind(builder));
return tasks;
}
run(platform: string, debug: boolean = false): Task[] {
const runner = Runner.new(this.config, platform, debug);
return [runner.prepare.bind(runner), runner.call.bind(runner)];
}
test(platform: string, debug: boolean = true): Task[] {
return this.build(platform, debug).concat(this.run(platform, debug));
}
pack(platform: string, name: string) {
const packer = Packer.new(this.config, platform, name);
return [packer.prepare.bind(packer), packer.call.bind(packer)];
}
compile(external_gulp?: gulp.Gulp): Record<string, TaskFunction> {
const result: Record<string, TaskFunction> = {};
const _gulp = external_gulp || gulp;
for (const platform of this.platforms) {
result[`${this.config.name}:${platform}:build`] = _gulp.series(this.build(platform));
if (Runner.factory[platform]) {
result[`${this.config.name}:${platform}:run`] = _gulp.series(this.run(platform));
result[`${this.config.name}:${platform}:test`] = _gulp.series(this.test(platform));
}
if (Packer.factory[platform]) {
for (const name of Object.keys(Packer.factory[platform])) {
result[`${this.config.name}:${platform}:${name}`] = _gulp.series(this.pack(platform, name));
}
}
}
return result;
}
register(external_gulp?: gulp.Gulp) {
const _gulp = external_gulp || gulp;
for (const [k, v] of Object.entries(this.compile(_gulp))) {
_gulp.task(k, v);
}
}
// TODO:
static useRuffle() {
Runner.register(Platform.FLASH, RuffleRunner);
}
}
+175
View File
@@ -0,0 +1,175 @@
import dateformat from "dateformat";
import gulp from "gulp";
import gulpClean from "gulp-clean";
import template from "lodash.template";
import os from "os";
import type { Task } from "undertaker";
import { Builder, Project } from ".";
import { System } from "../common/system";
import { Config, type ConfigParams } from "../core/config";
import { Sdk } from "../core/sdk";
import { Platform } from "../core/type";
import { Haxe } from "../impl/haxe";
export interface PresetConfig {
SdkDir?: string;
BuildDir?: string;
Develop?: boolean;
UseRuffle?: boolean;
Key?: any;
}
export const DEFAULT_CONFIG: PresetConfig = {
SdkDir: "$HOME/sdk",
};
export interface ProjectPreset {
buildSystem?: string;
platforms?: string[];
config: ConfigParams;
}
export class Preset {
public options: Record<string, ProjectPreset>;
public config: PresetConfig;
public packageInfo: Record<string, any>;
constructor(options: Record<string, ProjectPreset>, config?: PresetConfig, packageInfo?: Record<string, any>) {
this.config = Object.assign(DEFAULT_CONFIG, config || {});
this.packageInfo = packageInfo || {};
for (const [k, v] of Object.entries(options)) {
options[k] = this.fillPreset(v);
}
this.options = options;
}
private fillPreset(preset: ProjectPreset): ProjectPreset {
const configTemplate = template(JSON.stringify(preset));
return JSON.parse(
configTemplate({ config: this.config, package: this.packageInfo, env: process.env, dateformat: dateformat }),
);
}
compile(): Project[] {
const config = new Config(this.options["default"]?.config);
if (this.packageInfo.haxeDependencies) {
config.update({ libs: this.packageInfo.haxeDependencies });
}
const projects: Project[] = [];
for (const [k, v] of Object.entries(this.options)) {
if (k == "default") {
continue;
}
const projectConfig = config.branch(Object.assign(v.config, { name: k }));
projects.push(new Project(v.buildSystem!, v.platforms!, projectConfig));
}
return projects;
}
register(external_gulp?: gulp.Gulp, additional_tasks?: string[]) {
const _gulp = external_gulp || gulp;
const resolvePath = (path: string) => path.replace("$HOME", os.homedir());
if (this.config.UseRuffle) {
Project.useRuffle();
}
if (this.packageInfo.haxe) {
Haxe.VERSION = this.packageInfo.haxe;
}
if (this.config.SdkDir) {
Sdk.dir = resolvePath(this.config.SdkDir);
}
if (this.config.BuildDir) {
Haxe.buildDir = resolvePath(this.config.BuildDir);
}
_gulp.task("clean", () => {
return _gulp.src("target/*", { read: false }).pipe(gulpClean());
});
const projects = this.compile();
const project = projects[0];
_gulp.task("setup", () => {
return Promise.all(
project.platforms.map((platform) => Builder.new(project.config, platform, project.buildSystem).prepare()),
);
});
const protohx = project.hasLib("protohx");
if (protohx) {
_gulp.task("protohx:generate", () =>
new Haxe().haxelib(["run", "protohx", "generate", "protohx.json"]).then((result: any) => {
if (result.stdout.indexOf("FAIL") > -1) {
throw result.stdout;
}
}),
);
}
for (const project of projects) {
project.register(_gulp);
}
const defaultSeries: Task[] = [_gulp.task("clean")!, _gulp.task("setup")!];
if (protohx) {
defaultSeries.push(_gulp.task("protohx:generate")!);
}
if (additional_tasks) {
for (const task of additional_tasks) {
defaultSeries.push(_gulp.task(task)!);
}
}
for (const project of projects) {
for (const platform of project.platforms) {
switch (platform) {
case Platform.FLASH:
defaultSeries.push(_gulp.task(`${project.config.name}:${platform}:build`)!);
defaultSeries.push(_gulp.task(`${project.config.name}:${platform}:html`)!);
break;
case Platform.HTML5:
defaultSeries.push(_gulp.task(`${project.config.name}:${platform}:build`)!);
break;
case Platform.LINUX:
if (System.isLinux) {
defaultSeries.push(_gulp.task(`${project.config.name}:${platform}:build`)!);
defaultSeries.push(_gulp.task(`${project.config.name}:${platform}:archive`)!);
defaultSeries.push(_gulp.task(`${project.config.name}:${platform}:deb`)!);
}
break;
case Platform.CPP:
if (System.isLinux) {
defaultSeries.push(_gulp.task(`${project.config.name}:${platform}:build`)!);
}
break;
case Platform.NEKO:
if (System.isLinux) {
defaultSeries.push(_gulp.task(`${project.config.name}:${platform}:build`)!);
}
break;
case Platform.ANDROID:
if (System.isLinux) {
defaultSeries.push(_gulp.task(`${project.config.name}:${platform}:build`)!);
}
break;
case Platform.WINDOWS:
if (System.isWindows) {
defaultSeries.push(_gulp.task(`${project.config.name}:${platform}:build`)!);
defaultSeries.push(_gulp.task(`${project.config.name}:${platform}:archive`)!);
defaultSeries.push(_gulp.task(`${project.config.name}:${platform}:installer`)!);
}
break;
}
}
}
return _gulp.series(defaultSeries);
}
}
+53 -77
View File
@@ -1,83 +1,61 @@
var cp = require('child_process'); import colors from "ansi-colors";
var path = require('path'); import cp from "child_process";
var stream = require('stream'); import { defaults, template } from "lodash";
var util = require('util'); import path from "path";
var defaults = require('lodash.defaults'); import stream from "stream";
var applyTemplate = require('lodash.template'); import util from "util";
var Vinyl = require('vinyl'); import Vinyl from "vinyl";
var colors = require('ansi-colors');
/** export class Command {
* Creates a new `gulp-run` command. private command: string;
* private isWindows: boolean;
* @param {string} command private options: any;
* @param {object} options
*/
export function Command(command, options?) {
var previousPath;
constructor(command: string, options?: any) {
this.command = command; this.command = command;
this.isWindows = process.platform.lastIndexOf("win") === 0;
// We're on Windows if `process.platform` starts with "win", i.e. "win32".
this.isWindows = (process.platform.lastIndexOf('win') === 0);
// the cwd and environment of the command are the same as the main node
// process by default.
this.options = defaults(options || {}, { this.options = defaults(options || {}, {
cwd: process.cwd(), cwd: process.cwd(),
env: process.env, env: process.env,
verbosity: (options && options.silent) ? 1 : 2, verbosity: options && options.silent ? 1 : 2,
usePowerShell: false usePowerShell: false,
}); });
// include node_modules/.bin on the path when we execute the command. let previousPath;
previousPath = this.options.env.PATH; previousPath = this.options.env.PATH;
this.options.env.PATH = path.join(this.options.cwd, 'node_modules', '.bin'); this.options.env.PATH = path.join(this.options.cwd, "node_modules", ".bin");
this.options.env.PATH += path.delimiter; this.options.env.PATH += path.delimiter;
this.options.env.PATH += previousPath; this.options.env.PATH += previousPath;
} }
/** exec(stdin?: any, callback?: any) {
* Execute the command, invoking the callback when the command exits. let fileName;
* Returns a Vinyl file wrapping the command's stdout. let directory;
* let subShell;
* @param {string} stdin
* @param {function} callback
* @return {Stream}
*/
Command.prototype.exec = function exec(stdin, callback) {
var self = this;
var command;
var fileName;
var directory;
var subShell;
var log;
var err;
var stdout;
// parse the arguments, both are optional. // parse the arguments, both are optional.
// after parsing, stdin is a vinyl file to use as standard input to // after parsing, stdin is a vinyl file to use as standard input to
// the command (possibly empty), and callback is a function. // the command (possibly empty), and callback is a function.
if (typeof stdin === 'function') { if (typeof stdin === "function") {
callback = stdin; callback = stdin;
stdin = undefined; stdin = undefined;
} else if (typeof callback !== 'function') { } else if (typeof callback !== "function") {
callback = function noop() {}; callback = function noop() {};
} }
if (!(stdin instanceof Vinyl)) { if (!(stdin instanceof Vinyl)) {
fileName = this.command.split(' ')[0]; fileName = this.command.split(" ")[0];
directory = path.join(this.options.cwd, fileName); directory = path.join(this.options.cwd, fileName);
if (typeof stdin === 'string') { if (typeof stdin === "string") {
stdin = new Vinyl({ stdin = new Vinyl({
path: directory, path: directory,
contents: new Buffer(stdin) contents: new Buffer(stdin),
}); });
} else if (stdin instanceof Buffer || stdin instanceof stream.Readable) { } else if (stdin instanceof Buffer || stdin instanceof stream.Readable) {
stdin = new Vinyl({ stdin = new Vinyl({
path: directory, path: directory,
contents: stdin contents: stdin,
}); });
} else { } else {
stdin = new Vinyl(stdin); stdin = new Vinyl(stdin);
@@ -91,27 +69,27 @@ Command.prototype.exec = function exec(stdin, callback) {
// execute the command. // execute the command.
// we spawn the command in a subshell, so things like i/o redirection // we spawn the command in a subshell, so things like i/o redirection
// just work. e.g. `echo hello world >> ./hello.txt` works as expected. // just work. e.g. `echo hello world >> ./hello.txt` works as expected.
command = applyTemplate(this.command)({ const command = template(this.command)({
file: stdin file: stdin,
}); });
if (this.isWindows && this.options.usePowerShell) { if (this.isWindows && this.options.usePowerShell) {
// windows powershell // windows powershell
subShell = cp.spawn('powershell.exe', ['-NonInteractive', '-NoLogo', '-Command', command], { subShell = cp.spawn("powershell.exe", ["-NonInteractive", "-NoLogo", "-Command", command], {
env: this.options.env, env: this.options.env,
cwd: this.options.cwd cwd: this.options.cwd,
}); });
} else if (this.isWindows) { } else if (this.isWindows) {
// windows cmd.exe // windows cmd.exe
subShell = cp.spawn('cmd.exe', ['/c', command], { subShell = cp.spawn("cmd.exe", ["/c", command], {
env: this.options.env, env: this.options.env,
cwd: this.options.cwd cwd: this.options.cwd,
}); });
} else { } else {
// POSIX shell // POSIX shell
subShell = cp.spawn('sh', ['-c', command], { subShell = cp.spawn("sh", ["-c", command], {
env: this.options.env, env: this.options.env,
cwd: this.options.cwd cwd: this.options.cwd,
}); });
} }
@@ -123,17 +101,17 @@ Command.prototype.exec = function exec(stdin, callback) {
// prevents overlaping output of multiple commands) // prevents overlaping output of multiple commands)
// - if verbosity equals to 1, the command's stderr is buffered as in 2, but // - if verbosity equals to 1, the command's stderr is buffered as in 2, but
// the stdout is silenced. // the stdout is silenced.
log = new stream.PassThrough(); const log = new stream.PassThrough();
function sendLog(context) { const sendLog = (context: any) => {
var title = util.format( var title = util.format(
'$ %s%s', "$ %s%s",
colors.blue(command), colors.blue(command),
(self.options.verbosity < 2) ? colors.grey(' # Silenced\n') : '\n' this.options.verbosity < 2 ? colors.grey(" # Silenced\n") : "\n",
); );
context.write(title); context.write(title);
} };
switch (this.options.verbosity) { switch (this.options.verbosity) {
case 3: case 3:
@@ -151,19 +129,21 @@ Command.prototype.exec = function exec(stdin, callback) {
} }
// setup the cleanup proceedure for when the command finishes. // setup the cleanup proceedure for when the command finishes.
subShell.once('close', function handleSubShellClose() { subShell.once("close", function handleSubShellClose() {
// write the buffered output to stdout // write the buffered output to stdout
var content = log.read(); const content = log.read();
if (content !== null) { if (content !== null) {
process.stdout.write(content); process.stdout.write(content);
} }
}); });
subShell.once('exit', function handleSubShellExit(code) { subShell.once("exit", function handleSubShellExit(code) {
// report an error if the command exited with a non-zero exit code. // report an error if the command exited with a non-zero exit code.
if (code !== 0) { if (code !== 0) {
err = new Error(util.format('Command `%s` exited with code %s', command, code)); const err: Error & { status?: number | null } = new Error(
util.format("Command `%s` exited with code %s", command, code),
);
err.status = code; err.status = code;
return callback(err); return callback(err);
@@ -174,20 +154,16 @@ Command.prototype.exec = function exec(stdin, callback) {
// the file wrapping stdout is as the one wrapping stdin (same metadata) // the file wrapping stdout is as the one wrapping stdin (same metadata)
// with different contents. // with different contents.
stdout = stdin.clone(); const stdout = stdin.clone({ path: "stdout" });
stdout.contents = subShell.stdout.pipe(new stream.PassThrough()); stdout.contents = subShell.stdout.pipe(new stream.PassThrough());
// finally, write the input to the process's stdin. // finally, write the input to the process's stdin.
//stdin.pipe(subShell.stdin); //ToDo: //stdin.pipe(subShell.stdin); //TODO:
return stdout; return stdout;
}; }
/** toString() {
* Returns the command template.
*
* @return {string}
*/
Command.prototype.toString = function toString() {
return this.command; return this.command;
}; }
}
+14 -61
View File
@@ -1,71 +1,24 @@
/** import { Transform, type TransformCallback } from "stream";
* Pipe shell commands in gulp.
* @module gulp-run
*/
import { Command } from "./command"; import { Command } from "./command";
var inherit = require("util").inherits; export class RunTransform extends Transform {
var Transform = require("stream").Transform; private command: Command;
/** constructor(template: string, options?: any) {
* Creates a GulpRunner. super({ objectMode: true });
* this.command = new Command(template, options || {});
* A GulpRunner is a Vinyl transform stream that spawns a child process to
* transform the file. A separate process is spawned to handle each file
* passing through the stream.
*
* @param {string} template
* @param {object} options
*/
function GulpRunner(template, options) {
if (!(this instanceof GulpRunner)) {
return new GulpRunner(template, options);
} }
this.command = new Command(template, options || {}); _transform(chunk: any, encoding: BufferEncoding, callback: TransformCallback): void {
Transform.call(this, { objectMode: true }); const stdout = this.command.exec(chunk, callback);
} this.push(stdout);
}
/** exec(stdin?: any, callback?: any) {
* @extends {Stream.Transform}
*/
inherit(GulpRunner, Transform);
/**
* @param {string} file
* @param {string} encoding
* @param {function} callback
* @return {void}
*/
GulpRunner.prototype._transform = function _transform(file, encoding, callback) {
var newfile = this.command.exec(file, callback);
this.push(newfile);
};
/**
* Writes `stdin` to itself and returns itself.
*
* Whenever an object is written into the GulpRunner, a new process is
* spawned taking that data as standard input, and a Vinyl file wrapping the
* process's standard output is pushed downstream.
*
* `stdin` may be a String, Buffer, Readable stream, or Vinyl file.
*
* @param {mixed} stdin
* @param {function} callback
* @return {GulpRunner}
*/
GulpRunner.prototype.exec = function exec(stdin, callback) {
this.write(stdin, callback); this.write(stdin, callback);
this.end(); this.end();
return this; return this;
}; }
}
/** export default (template: string, options?: any) => new RunTransform(template, options);
* @static
* @type {Command}
*/
GulpRunner.Command = Command;
export default GulpRunner;
+22
View File
@@ -0,0 +1,22 @@
import assert from "node:assert/strict";
import { existsSync, mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
import { Downloader } from "../dist/index.mjs";
const resolveTargetDir = () => mkdtempSync(join(tmpdir(), "test-"));
const TEST_DATA = {
"https://home.shmyga.ru/public/sdk/haxe/haxe-4.2.5-win.zip": "haxe.exe",
"https://home.shmyga.ru/public/sdk/haxe/haxe-4.2.5-linux64.tar.gz": "haxe",
"https://home.shmyga.ru/public/test.txt": "test.txt",
};
for (const [url, file] of Object.entries(TEST_DATA)) {
test(`Test download: ${url}`, async () => {
const target = resolveTargetDir();
await Downloader.download(url, target);
assert(existsSync(join(target, file)));
});
}
+2 -1
View File
@@ -14,7 +14,8 @@
"esModuleInterop": true, "esModuleInterop": true,
"isolatedModules": true, "isolatedModules": true,
"verbatimModuleSyntax": true, "verbatimModuleSyntax": true,
"skipLibCheck": true "skipLibCheck": true,
"noImplicitThis": false,
}, },
"include": ["src"] "include": ["src"]
} }