commit
45d3fa9f89
@ -1,7 +1,7 @@
|
|||||||
@IF EXIST "%~dp0\node.exe" (
|
@IF EXIST "%~dp0\node.exe" (
|
||||||
"%~dp0\node.exe" "%~dp0\..\semver\bin\semver" %*
|
"%~dp0\node.exe" "%~dp0\..\semver\bin\semver.js" %*
|
||||||
) ELSE (
|
) ELSE (
|
||||||
@SETLOCAL
|
@SETLOCAL
|
||||||
@SET PATHEXT=%PATHEXT:;.JS;=;%
|
@SET PATHEXT=%PATHEXT:;.JS;=;%
|
||||||
node "%~dp0\..\semver\bin\semver" %*
|
node "%~dp0\..\semver\bin\semver.js" %*
|
||||||
)
|
)
|
||||||
@ -1,7 +0,0 @@
|
|||||||
Copyright 2019 GitHub
|
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
||||||
|
|
||||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
||||||
|
|
||||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
||||||
@ -1,81 +1,140 @@
|
|||||||
# `@actions/core`
|
# `@actions/core`
|
||||||
|
|
||||||
> Core functions for setting results, logging, registering secrets and exporting variables across actions
|
> Core functions for setting results, logging, registering secrets and exporting variables across actions
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
#### Inputs/Outputs
|
### Import the package
|
||||||
|
|
||||||
You can use this library to get inputs or set outputs:
|
```js
|
||||||
|
// javascript
|
||||||
```
|
const core = require('@actions/core');
|
||||||
const core = require('@actions/core');
|
|
||||||
|
// typescript
|
||||||
const myInput = core.getInput('inputName', { required: true });
|
import * as core from '@actions/core';
|
||||||
|
```
|
||||||
// Do stuff
|
|
||||||
|
#### Inputs/Outputs
|
||||||
core.setOutput('outputKey', 'outputVal');
|
|
||||||
```
|
Action inputs can be read with `getInput`. Outputs can be set with `setOutput` which makes them available to be mapped into inputs of other actions to ensure they are decoupled.
|
||||||
|
|
||||||
#### Exporting variables/secrets
|
```js
|
||||||
|
const myInput = core.getInput('inputName', { required: true });
|
||||||
You can also export variables and secrets for future steps. Variables get set in the environment automatically, while secrets must be scoped into the environment from a workflow using `{{ secret.FOO }}`. Secrets will also be masked from the logs:
|
|
||||||
|
core.setOutput('outputKey', 'outputVal');
|
||||||
```
|
```
|
||||||
const core = require('@actions/core');
|
|
||||||
|
#### Exporting variables
|
||||||
// Do stuff
|
|
||||||
|
Since each step runs in a separate process, you can use `exportVariable` to add it to this step and future steps environment blocks.
|
||||||
core.exportVariable('envVar', 'Val');
|
|
||||||
core.exportSecret('secretVar', variableWithSecretValue);
|
```js
|
||||||
```
|
core.exportVariable('envVar', 'Val');
|
||||||
|
```
|
||||||
#### PATH Manipulation
|
|
||||||
|
#### Setting a secret
|
||||||
You can explicitly add items to the path for all remaining steps in a workflow:
|
|
||||||
|
Setting a secret registers the secret with the runner to ensure it is masked in logs.
|
||||||
```
|
|
||||||
const core = require('@actions/core');
|
```js
|
||||||
|
core.setSecret('myPassword');
|
||||||
core.addPath('pathToTool');
|
```
|
||||||
```
|
|
||||||
|
#### PATH Manipulation
|
||||||
#### Exit codes
|
|
||||||
|
To make a tool's path available in the path for the remainder of the job (without altering the machine or containers state), use `addPath`. The runner will prepend the path given to the jobs PATH.
|
||||||
You should use this library to set the failing exit code for your action:
|
|
||||||
|
```js
|
||||||
```
|
core.addPath('/path/to/mytool');
|
||||||
const core = require('@actions/core');
|
```
|
||||||
|
|
||||||
try {
|
#### Exit codes
|
||||||
// Do stuff
|
|
||||||
}
|
You should use this library to set the failing exit code for your action. If status is not set and the script runs to completion, that will lead to a success.
|
||||||
catch (err) {
|
|
||||||
// setFailed logs the message and sets a failing exit code
|
```js
|
||||||
core.setFailed(`Action failed with error ${err}`);
|
const core = require('@actions/core');
|
||||||
}
|
|
||||||
|
try {
|
||||||
```
|
// Do stuff
|
||||||
|
}
|
||||||
#### Logging
|
catch (err) {
|
||||||
|
// setFailed logs the message and sets a failing exit code
|
||||||
Finally, this library provides some utilities for logging:
|
core.setFailed(`Action failed with error ${err}`);
|
||||||
|
}
|
||||||
```
|
|
||||||
const core = require('@actions/core');
|
Note that `setNeutral` is not yet implemented in actions V2 but equivalent functionality is being planned.
|
||||||
|
|
||||||
const myInput = core.getInput('input');
|
```
|
||||||
try {
|
|
||||||
core.debug('Inside try block');
|
#### Logging
|
||||||
|
|
||||||
if (!myInput) {
|
Finally, this library provides some utilities for logging. Note that debug logging is hidden from the logs by default. This behavior can be toggled by enabling the [Step Debug Logs](../../docs/action-debugging.md#step-debug-logs).
|
||||||
core.warning('myInput wasnt set');
|
|
||||||
}
|
```js
|
||||||
|
const core = require('@actions/core');
|
||||||
// Do stuff
|
|
||||||
}
|
const myInput = core.getInput('input');
|
||||||
catch (err) {
|
try {
|
||||||
core.error('Error ${err}, action may still succeed though');
|
core.debug('Inside try block');
|
||||||
}
|
|
||||||
```
|
if (!myInput) {
|
||||||
|
core.warning('myInput was not set');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Do stuff
|
||||||
|
}
|
||||||
|
catch (err) {
|
||||||
|
core.error(`Error ${err}, action may still succeed though`);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
This library can also wrap chunks of output in foldable groups.
|
||||||
|
|
||||||
|
```js
|
||||||
|
const core = require('@actions/core')
|
||||||
|
|
||||||
|
// Manually wrap output
|
||||||
|
core.startGroup('Do some function')
|
||||||
|
doSomeFunction()
|
||||||
|
core.endGroup()
|
||||||
|
|
||||||
|
// Wrap an asynchronous function call
|
||||||
|
const result = await core.group('Do something async', async () => {
|
||||||
|
const response = await doSomeHTTPRequest()
|
||||||
|
return response
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Action state
|
||||||
|
|
||||||
|
You can use this library to save state and get state for sharing information between a given wrapper action:
|
||||||
|
|
||||||
|
**action.yml**
|
||||||
|
```yaml
|
||||||
|
name: 'Wrapper action sample'
|
||||||
|
inputs:
|
||||||
|
name:
|
||||||
|
default: 'GitHub'
|
||||||
|
runs:
|
||||||
|
using: 'node12'
|
||||||
|
main: 'main.js'
|
||||||
|
post: 'cleanup.js'
|
||||||
|
```
|
||||||
|
|
||||||
|
In action's `main.js`:
|
||||||
|
|
||||||
|
```js
|
||||||
|
const core = require('@actions/core');
|
||||||
|
|
||||||
|
core.saveState("pidToKill", 12345);
|
||||||
|
```
|
||||||
|
|
||||||
|
In action's `cleanup.js`:
|
||||||
|
```js
|
||||||
|
const core = require('@actions/core');
|
||||||
|
|
||||||
|
var pid = core.getState("pidToKill");
|
||||||
|
|
||||||
|
process.kill(pid);
|
||||||
|
```
|
||||||
@ -1,16 +1,16 @@
|
|||||||
interface CommandProperties {
|
interface CommandProperties {
|
||||||
[key: string]: string;
|
[key: string]: string;
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* Commands
|
* Commands
|
||||||
*
|
*
|
||||||
* Command Format:
|
* Command Format:
|
||||||
* ##[name key=value;key=value]message
|
* ##[name key=value;key=value]message
|
||||||
*
|
*
|
||||||
* Examples:
|
* Examples:
|
||||||
* ##[warning]This is the user warning message
|
* ##[warning]This is the user warning message
|
||||||
* ##[set-secret name=mypassword]definatelyNotAPassword!
|
* ##[set-secret name=mypassword]definitelyNotAPassword!
|
||||||
*/
|
*/
|
||||||
export declare function issueCommand(command: string, properties: CommandProperties, message: string): void;
|
export declare function issueCommand(command: string, properties: CommandProperties, message: string): void;
|
||||||
export declare function issue(name: string, message: string): void;
|
export declare function issue(name: string, message?: string): void;
|
||||||
export {};
|
export {};
|
||||||
|
|||||||
@ -1,66 +1,66 @@
|
|||||||
"use strict";
|
"use strict";
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
const os = require("os");
|
const os = require("os");
|
||||||
/**
|
/**
|
||||||
* Commands
|
* Commands
|
||||||
*
|
*
|
||||||
* Command Format:
|
* Command Format:
|
||||||
* ##[name key=value;key=value]message
|
* ##[name key=value;key=value]message
|
||||||
*
|
*
|
||||||
* Examples:
|
* Examples:
|
||||||
* ##[warning]This is the user warning message
|
* ##[warning]This is the user warning message
|
||||||
* ##[set-secret name=mypassword]definatelyNotAPassword!
|
* ##[set-secret name=mypassword]definitelyNotAPassword!
|
||||||
*/
|
*/
|
||||||
function issueCommand(command, properties, message) {
|
function issueCommand(command, properties, message) {
|
||||||
const cmd = new Command(command, properties, message);
|
const cmd = new Command(command, properties, message);
|
||||||
process.stdout.write(cmd.toString() + os.EOL);
|
process.stdout.write(cmd.toString() + os.EOL);
|
||||||
}
|
}
|
||||||
exports.issueCommand = issueCommand;
|
exports.issueCommand = issueCommand;
|
||||||
function issue(name, message) {
|
function issue(name, message = '') {
|
||||||
issueCommand(name, {}, message);
|
issueCommand(name, {}, message);
|
||||||
}
|
}
|
||||||
exports.issue = issue;
|
exports.issue = issue;
|
||||||
const CMD_PREFIX = '##[';
|
const CMD_STRING = '::';
|
||||||
class Command {
|
class Command {
|
||||||
constructor(command, properties, message) {
|
constructor(command, properties, message) {
|
||||||
if (!command) {
|
if (!command) {
|
||||||
command = 'missing.command';
|
command = 'missing.command';
|
||||||
}
|
}
|
||||||
this.command = command;
|
this.command = command;
|
||||||
this.properties = properties;
|
this.properties = properties;
|
||||||
this.message = message;
|
this.message = message;
|
||||||
}
|
}
|
||||||
toString() {
|
toString() {
|
||||||
let cmdStr = CMD_PREFIX + this.command;
|
let cmdStr = CMD_STRING + this.command;
|
||||||
if (this.properties && Object.keys(this.properties).length > 0) {
|
if (this.properties && Object.keys(this.properties).length > 0) {
|
||||||
cmdStr += ' ';
|
cmdStr += ' ';
|
||||||
for (const key in this.properties) {
|
for (const key in this.properties) {
|
||||||
if (this.properties.hasOwnProperty(key)) {
|
if (this.properties.hasOwnProperty(key)) {
|
||||||
const val = this.properties[key];
|
const val = this.properties[key];
|
||||||
if (val) {
|
if (val) {
|
||||||
// safely append the val - avoid blowing up when attempting to
|
// safely append the val - avoid blowing up when attempting to
|
||||||
// call .replace() if message is not a string for some reason
|
// call .replace() if message is not a string for some reason
|
||||||
cmdStr += `${key}=${escape(`${val || ''}`)};`;
|
cmdStr += `${key}=${escape(`${val || ''}`)},`;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
cmdStr += ']';
|
cmdStr += CMD_STRING;
|
||||||
// safely append the message - avoid blowing up when attempting to
|
// safely append the message - avoid blowing up when attempting to
|
||||||
// call .replace() if message is not a string for some reason
|
// call .replace() if message is not a string for some reason
|
||||||
const message = `${this.message || ''}`;
|
const message = `${this.message || ''}`;
|
||||||
cmdStr += escapeData(message);
|
cmdStr += escapeData(message);
|
||||||
return cmdStr;
|
return cmdStr;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
function escapeData(s) {
|
function escapeData(s) {
|
||||||
return s.replace(/\r/g, '%0D').replace(/\n/g, '%0A');
|
return s.replace(/\r/g, '%0D').replace(/\n/g, '%0A');
|
||||||
}
|
}
|
||||||
function escape(s) {
|
function escape(s) {
|
||||||
return s
|
return s
|
||||||
.replace(/\r/g, '%0D')
|
.replace(/\r/g, '%0D')
|
||||||
.replace(/\n/g, '%0A')
|
.replace(/\n/g, '%0A')
|
||||||
.replace(/]/g, '%5D')
|
.replace(/]/g, '%5D')
|
||||||
.replace(/;/g, '%3B');
|
.replace(/;/g, '%3B');
|
||||||
}
|
}
|
||||||
//# sourceMappingURL=command.js.map
|
//# sourceMappingURL=command.js.map
|
||||||
@ -1 +1 @@
|
|||||||
{"version":3,"file":"command.js","sourceRoot":"","sources":["../src/command.ts"],"names":[],"mappings":";;AAAA,yBAAwB;AAQxB;;;;;;;;;GASG;AACH,SAAgB,YAAY,CAC1B,OAAe,EACf,UAA6B,EAC7B,OAAe;IAEf,MAAM,GAAG,GAAG,IAAI,OAAO,CAAC,OAAO,EAAE,UAAU,EAAE,OAAO,CAAC,CAAA;IACrD,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,QAAQ,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,CAAA;AAC/C,CAAC;AAPD,oCAOC;AAED,SAAgB,KAAK,CAAC,IAAY,EAAE,OAAe;IACjD,YAAY,CAAC,IAAI,EAAE,EAAE,EAAE,OAAO,CAAC,CAAA;AACjC,CAAC;AAFD,sBAEC;AAED,MAAM,UAAU,GAAG,KAAK,CAAA;AAExB,MAAM,OAAO;IAKX,YAAY,OAAe,EAAE,UAA6B,EAAE,OAAe;QACzE,IAAI,CAAC,OAAO,EAAE;YACZ,OAAO,GAAG,iBAAiB,CAAA;SAC5B;QAED,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;QACtB,IAAI,CAAC,UAAU,GAAG,UAAU,CAAA;QAC5B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;IACxB,CAAC;IAED,QAAQ;QACN,IAAI,MAAM,GAAG,UAAU,GAAG,IAAI,CAAC,OAAO,CAAA;QAEtC,IAAI,IAAI,CAAC,UAAU,IAAI,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE;YAC9D,MAAM,IAAI,GAAG,CAAA;YACb,KAAK,MAAM,GAAG,IAAI,IAAI,CAAC,UAAU,EAAE;gBACjC,IAAI,IAAI,CAAC,UAAU,CAAC,cAAc,CAAC,GA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;IACf,CAAC;CACF;AAED,SAAS,UAAU,CAAC,CAAS;IAC3B,OAAO,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC,CAAA;AACtD,CAAC;AAED,SAAS,MAAM,CAAC,CAAS;IACvB,OAAO,CAAC;SACL,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC;SACrB,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC;SACrB,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC;SACpB,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC,CAAA;AACzB,CAAC"}
|
||||||
@ -1,73 +1,112 @@
|
|||||||
/**
|
/**
|
||||||
* Interface for getInput options
|
* Interface for getInput options
|
||||||
*/
|
*/
|
||||||
export interface InputOptions {
|
export interface InputOptions {
|
||||||
/** Optional. Whether the input is required. If required and not present, will throw. Defaults to false */
|
/** Optional. Whether the input is required. If required and not present, will throw. Defaults to false */
|
||||||
required?: boolean;
|
required?: boolean;
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* The code to exit an action
|
* The code to exit an action
|
||||||
*/
|
*/
|
||||||
export declare enum ExitCode {
|
export declare enum ExitCode {
|
||||||
/**
|
/**
|
||||||
* A code indicating that the action was successful
|
* A code indicating that the action was successful
|
||||||
*/
|
*/
|
||||||
Success = 0,
|
Success = 0,
|
||||||
/**
|
/**
|
||||||
* A code indicating that the action was a failure
|
* A code indicating that the action was a failure
|
||||||
*/
|
*/
|
||||||
Failure = 1
|
Failure = 1
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* sets env variable for this action and future actions in the job
|
* Sets env variable for this action and future actions in the job
|
||||||
* @param name the name of the variable to set
|
* @param name the name of the variable to set
|
||||||
* @param val the value of the variable
|
* @param val the value of the variable
|
||||||
*/
|
*/
|
||||||
export declare function exportVariable(name: string, val: string): void;
|
export declare function exportVariable(name: string, val: string): void;
|
||||||
/**
|
/**
|
||||||
* exports the variable and registers a secret which will get masked from logs
|
* Registers a secret which will get masked from logs
|
||||||
* @param name the name of the variable to set
|
* @param secret value of the secret
|
||||||
* @param val value of the secret
|
*/
|
||||||
*/
|
export declare function setSecret(secret: string): void;
|
||||||
export declare function exportSecret(name: string, val: string): void;
|
/**
|
||||||
/**
|
* Prepends inputPath to the PATH (for this action and future actions)
|
||||||
* Prepends inputPath to the PATH (for this action and future actions)
|
* @param inputPath
|
||||||
* @param inputPath
|
*/
|
||||||
*/
|
export declare function addPath(inputPath: string): void;
|
||||||
export declare function addPath(inputPath: string): void;
|
/**
|
||||||
/**
|
* Gets the value of an input. The value is also trimmed.
|
||||||
* Gets the value of an input. The value is also trimmed.
|
*
|
||||||
*
|
* @param name name of the input to get
|
||||||
* @param name name of the input to get
|
* @param options optional. See InputOptions.
|
||||||
* @param options optional. See InputOptions.
|
* @returns string
|
||||||
* @returns string
|
*/
|
||||||
*/
|
export declare function getInput(name: string, options?: InputOptions): string;
|
||||||
export declare function getInput(name: string, options?: InputOptions): string;
|
/**
|
||||||
/**
|
* Sets the value of an output.
|
||||||
* Sets the value of an output.
|
*
|
||||||
*
|
* @param name name of the output to set
|
||||||
* @param name name of the output to set
|
* @param value value to store
|
||||||
* @param value value to store
|
*/
|
||||||
*/
|
export declare function setOutput(name: string, value: string): void;
|
||||||
export declare function setOutput(name: string, value: string): void;
|
/**
|
||||||
/**
|
* Sets the action status to failed.
|
||||||
* Sets the action status to failed.
|
* When the action exits it will be with an exit code of 1
|
||||||
* When the action exits it will be with an exit code of 1
|
* @param message add error issue message
|
||||||
* @param message add error issue message
|
*/
|
||||||
*/
|
export declare function setFailed(message: string): void;
|
||||||
export declare function setFailed(message: string): void;
|
/**
|
||||||
/**
|
* Writes debug message to user log
|
||||||
* Writes debug message to user log
|
* @param message debug message
|
||||||
* @param message debug message
|
*/
|
||||||
*/
|
export declare function debug(message: string): void;
|
||||||
export declare function debug(message: string): void;
|
/**
|
||||||
/**
|
* Adds an error issue
|
||||||
* Adds an error issue
|
* @param message error issue message
|
||||||
* @param message error issue message
|
*/
|
||||||
*/
|
export declare function error(message: string): void;
|
||||||
export declare function error(message: string): void;
|
/**
|
||||||
/**
|
* Adds an warning issue
|
||||||
* Adds an warning issue
|
* @param message warning issue message
|
||||||
* @param message warning issue message
|
*/
|
||||||
*/
|
export declare function warning(message: string): void;
|
||||||
export declare function warning(message: string): void;
|
/**
|
||||||
|
* Writes info to log with console.log.
|
||||||
|
* @param message info message
|
||||||
|
*/
|
||||||
|
export declare function info(message: string): void;
|
||||||
|
/**
|
||||||
|
* Begin an output group.
|
||||||
|
*
|
||||||
|
* Output until the next `groupEnd` will be foldable in this group
|
||||||
|
*
|
||||||
|
* @param name The name of the output group
|
||||||
|
*/
|
||||||
|
export declare function startGroup(name: string): void;
|
||||||
|
/**
|
||||||
|
* End an output group.
|
||||||
|
*/
|
||||||
|
export declare function endGroup(): void;
|
||||||
|
/**
|
||||||
|
* Wrap an asynchronous function call in a group.
|
||||||
|
*
|
||||||
|
* Returns the same type as the function itself.
|
||||||
|
*
|
||||||
|
* @param name The name of the group
|
||||||
|
* @param fn The function to wrap in the group
|
||||||
|
*/
|
||||||
|
export declare function group<T>(name: string, fn: () => Promise<T>): Promise<T>;
|
||||||
|
/**
|
||||||
|
* Saves state for current action, the state can only be retrieved by this action's post job execution.
|
||||||
|
*
|
||||||
|
* @param name name of the state to store
|
||||||
|
* @param value value to store
|
||||||
|
*/
|
||||||
|
export declare function saveState(name: string, value: string): void;
|
||||||
|
/**
|
||||||
|
* Gets the value of an state set by this action's main execution.
|
||||||
|
*
|
||||||
|
* @param name name of the state to get
|
||||||
|
* @returns string
|
||||||
|
*/
|
||||||
|
export declare function getState(name: string): string;
|
||||||
|
|||||||
@ -1,116 +1,195 @@
|
|||||||
"use strict";
|
"use strict";
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||||
const command_1 = require("./command");
|
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||||
const path = require("path");
|
return new (P || (P = Promise))(function (resolve, reject) {
|
||||||
/**
|
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||||
* The code to exit an action
|
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); }
|
||||||
var ExitCode;
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||||
(function (ExitCode) {
|
});
|
||||||
/**
|
};
|
||||||
* A code indicating that the action was successful
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
*/
|
const command_1 = require("./command");
|
||||||
ExitCode[ExitCode["Success"] = 0] = "Success";
|
const os = require("os");
|
||||||
/**
|
const path = require("path");
|
||||||
* A code indicating that the action was a failure
|
/**
|
||||||
*/
|
* The code to exit an action
|
||||||
ExitCode[ExitCode["Failure"] = 1] = "Failure";
|
*/
|
||||||
})(ExitCode = exports.ExitCode || (exports.ExitCode = {}));
|
var ExitCode;
|
||||||
//-----------------------------------------------------------------------
|
(function (ExitCode) {
|
||||||
// Variables
|
/**
|
||||||
//-----------------------------------------------------------------------
|
* A code indicating that the action was successful
|
||||||
/**
|
*/
|
||||||
* sets env variable for this action and future actions in the job
|
ExitCode[ExitCode["Success"] = 0] = "Success";
|
||||||
* @param name the name of the variable to set
|
/**
|
||||||
* @param val the value of the variable
|
* A code indicating that the action was a failure
|
||||||
*/
|
*/
|
||||||
function exportVariable(name, val) {
|
ExitCode[ExitCode["Failure"] = 1] = "Failure";
|
||||||
process.env[name] = val;
|
})(ExitCode = exports.ExitCode || (exports.ExitCode = {}));
|
||||||
command_1.issueCommand('set-env', { name }, val);
|
//-----------------------------------------------------------------------
|
||||||
}
|
// Variables
|
||||||
exports.exportVariable = exportVariable;
|
//-----------------------------------------------------------------------
|
||||||
/**
|
/**
|
||||||
* exports the variable and registers a secret which will get masked from logs
|
* Sets env variable for this action and future actions in the job
|
||||||
* @param name the name of the variable to set
|
* @param name the name of the variable to set
|
||||||
* @param val value of the secret
|
* @param val the value of the variable
|
||||||
*/
|
*/
|
||||||
function exportSecret(name, val) {
|
function exportVariable(name, val) {
|
||||||
exportVariable(name, val);
|
process.env[name] = val;
|
||||||
command_1.issueCommand('set-secret', {}, val);
|
command_1.issueCommand('set-env', { name }, val);
|
||||||
}
|
}
|
||||||
exports.exportSecret = exportSecret;
|
exports.exportVariable = exportVariable;
|
||||||
/**
|
/**
|
||||||
* Prepends inputPath to the PATH (for this action and future actions)
|
* Registers a secret which will get masked from logs
|
||||||
* @param inputPath
|
* @param secret value of the secret
|
||||||
*/
|
*/
|
||||||
function addPath(inputPath) {
|
function setSecret(secret) {
|
||||||
command_1.issueCommand('add-path', {}, inputPath);
|
command_1.issueCommand('add-mask', {}, secret);
|
||||||
process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`;
|
}
|
||||||
}
|
exports.setSecret = setSecret;
|
||||||
exports.addPath = addPath;
|
/**
|
||||||
/**
|
* Prepends inputPath to the PATH (for this action and future actions)
|
||||||
* Gets the value of an input. The value is also trimmed.
|
* @param inputPath
|
||||||
*
|
*/
|
||||||
* @param name name of the input to get
|
function addPath(inputPath) {
|
||||||
* @param options optional. See InputOptions.
|
command_1.issueCommand('add-path', {}, inputPath);
|
||||||
* @returns string
|
process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`;
|
||||||
*/
|
}
|
||||||
function getInput(name, options) {
|
exports.addPath = addPath;
|
||||||
const val = process.env[`INPUT_${name.replace(' ', '_').toUpperCase()}`] || '';
|
/**
|
||||||
if (options && options.required && !val) {
|
* Gets the value of an input. The value is also trimmed.
|
||||||
throw new Error(`Input required and not supplied: ${name}`);
|
*
|
||||||
}
|
* @param name name of the input to get
|
||||||
return val.trim();
|
* @param options optional. See InputOptions.
|
||||||
}
|
* @returns string
|
||||||
exports.getInput = getInput;
|
*/
|
||||||
/**
|
function getInput(name, options) {
|
||||||
* Sets the value of an output.
|
const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || '';
|
||||||
*
|
if (options && options.required && !val) {
|
||||||
* @param name name of the output to set
|
throw new Error(`Input required and not supplied: ${name}`);
|
||||||
* @param value value to store
|
}
|
||||||
*/
|
return val.trim();
|
||||||
function setOutput(name, value) {
|
}
|
||||||
command_1.issueCommand('set-output', { name }, value);
|
exports.getInput = getInput;
|
||||||
}
|
/**
|
||||||
exports.setOutput = setOutput;
|
* Sets the value of an output.
|
||||||
//-----------------------------------------------------------------------
|
*
|
||||||
// Results
|
* @param name name of the output to set
|
||||||
//-----------------------------------------------------------------------
|
* @param value value to store
|
||||||
/**
|
*/
|
||||||
* Sets the action status to failed.
|
function setOutput(name, value) {
|
||||||
* When the action exits it will be with an exit code of 1
|
command_1.issueCommand('set-output', { name }, value);
|
||||||
* @param message add error issue message
|
}
|
||||||
*/
|
exports.setOutput = setOutput;
|
||||||
function setFailed(message) {
|
//-----------------------------------------------------------------------
|
||||||
process.exitCode = ExitCode.Failure;
|
// Results
|
||||||
error(message);
|
//-----------------------------------------------------------------------
|
||||||
}
|
/**
|
||||||
exports.setFailed = setFailed;
|
* Sets the action status to failed.
|
||||||
//-----------------------------------------------------------------------
|
* When the action exits it will be with an exit code of 1
|
||||||
// Logging Commands
|
* @param message add error issue message
|
||||||
//-----------------------------------------------------------------------
|
*/
|
||||||
/**
|
function setFailed(message) {
|
||||||
* Writes debug message to user log
|
process.exitCode = ExitCode.Failure;
|
||||||
* @param message debug message
|
error(message);
|
||||||
*/
|
}
|
||||||
function debug(message) {
|
exports.setFailed = setFailed;
|
||||||
command_1.issueCommand('debug', {}, message);
|
//-----------------------------------------------------------------------
|
||||||
}
|
// Logging Commands
|
||||||
exports.debug = debug;
|
//-----------------------------------------------------------------------
|
||||||
/**
|
/**
|
||||||
* Adds an error issue
|
* Writes debug message to user log
|
||||||
* @param message error issue message
|
* @param message debug message
|
||||||
*/
|
*/
|
||||||
function error(message) {
|
function debug(message) {
|
||||||
command_1.issue('error', message);
|
command_1.issueCommand('debug', {}, message);
|
||||||
}
|
}
|
||||||
exports.error = error;
|
exports.debug = debug;
|
||||||
/**
|
/**
|
||||||
* Adds an warning issue
|
* Adds an error issue
|
||||||
* @param message warning issue message
|
* @param message error issue message
|
||||||
*/
|
*/
|
||||||
function warning(message) {
|
function error(message) {
|
||||||
command_1.issue('warning', message);
|
command_1.issue('error', message);
|
||||||
}
|
}
|
||||||
exports.warning = warning;
|
exports.error = error;
|
||||||
|
/**
|
||||||
|
* Adds an warning issue
|
||||||
|
* @param message warning issue message
|
||||||
|
*/
|
||||||
|
function warning(message) {
|
||||||
|
command_1.issue('warning', message);
|
||||||
|
}
|
||||||
|
exports.warning = warning;
|
||||||
|
/**
|
||||||
|
* Writes info to log with console.log.
|
||||||
|
* @param message info message
|
||||||
|
*/
|
||||||
|
function info(message) {
|
||||||
|
process.stdout.write(message + os.EOL);
|
||||||
|
}
|
||||||
|
exports.info = info;
|
||||||
|
/**
|
||||||
|
* Begin an output group.
|
||||||
|
*
|
||||||
|
* Output until the next `groupEnd` will be foldable in this group
|
||||||
|
*
|
||||||
|
* @param name The name of the output group
|
||||||
|
*/
|
||||||
|
function startGroup(name) {
|
||||||
|
command_1.issue('group', name);
|
||||||
|
}
|
||||||
|
exports.startGroup = startGroup;
|
||||||
|
/**
|
||||||
|
* End an output group.
|
||||||
|
*/
|
||||||
|
function endGroup() {
|
||||||
|
command_1.issue('endgroup');
|
||||||
|
}
|
||||||
|
exports.endGroup = endGroup;
|
||||||
|
/**
|
||||||
|
* Wrap an asynchronous function call in a group.
|
||||||
|
*
|
||||||
|
* Returns the same type as the function itself.
|
||||||
|
*
|
||||||
|
* @param name The name of the group
|
||||||
|
* @param fn The function to wrap in the group
|
||||||
|
*/
|
||||||
|
function group(name, fn) {
|
||||||
|
return __awaiter(this, void 0, void 0, function* () {
|
||||||
|
startGroup(name);
|
||||||
|
let result;
|
||||||
|
try {
|
||||||
|
result = yield fn();
|
||||||
|
}
|
||||||
|
finally {
|
||||||
|
endGroup();
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
exports.group = group;
|
||||||
|
//-----------------------------------------------------------------------
|
||||||
|
// Wrapper action state
|
||||||
|
//-----------------------------------------------------------------------
|
||||||
|
/**
|
||||||
|
* Saves state for current action, the state can only be retrieved by this action's post job execution.
|
||||||
|
*
|
||||||
|
* @param name name of the state to store
|
||||||
|
* @param value value to store
|
||||||
|
*/
|
||||||
|
function saveState(name, value) {
|
||||||
|
command_1.issueCommand('save-state', { name }, value);
|
||||||
|
}
|
||||||
|
exports.saveState = saveState;
|
||||||
|
/**
|
||||||
|
* Gets the value of an state set by this action's main execution.
|
||||||
|
*
|
||||||
|
* @param name name of the state to get
|
||||||
|
* @returns string
|
||||||
|
*/
|
||||||
|
function getState(name) {
|
||||||
|
return process.env[`STATE_${name}`] || '';
|
||||||
|
}
|
||||||
|
exports.getState = getState;
|
||||||
//# sourceMappingURL=core.js.map
|
//# sourceMappingURL=core.js.map
|
||||||
@ -1 +1 @@
|
|||||||
{"version":3,"file":"core.js","sourceRoot":"","sources":["../src/core.ts"],"names":[],"mappings":";;AAAA,uCAA6C;AAE7C,6BAA4B;AAU5B;;GAEG;AACH,IAAY,QAUX;AAVD,WAAY,QAAQ;IAClB;;OAEG;IACH,6CAAW,CAAA;IAEX;;OAEG;IACH,6CAAW,CAAA;AACb,CAAC,EAVW,QAAQ,GAAR,gBAAQ,KAAR,gBAAQ,QAUnB;AAED,yEAAyE;AACzE,YAAY;AACZ,yEAAyE;AAEzE;;;;GAIG;AACH,SAAgB,cAAc,CAAC,IAAY,EAAE,GAAW;IACtD,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,GAAG,CAAA;IACvB,sBAAY,CAAC,SAAS,EAAE,EAAC,IAAI,EAAC,EAAE,GAAG,CAAC,CAAA;AACtC,CAAC;AAHD,wCAGC;AAED;;;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;IACrC,eAAK,CAAC,SAAS,EAAE,OAAO,CAAC,CAAA;AAC3B,CAAC;AAFD,0BAEC;AAED;;;GAGG;AACH,SAAgB,IAAI,CAAC,OAAe;IAClC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,OAAO,GAAG,EAAE,CAAC,GAAG,CAAC,CAAA;AACxC,CAAC;AAFD,oBAEC;AAED;;;;;;GAMG;AACH,SAAgB,UAAU,CAAC,IAAY;IACrC,eAAK,CAAC,OAAO,EAAE,IAAI,CAAC,CAAA;AACtB,CAAC;AAFD,gCAEC;AAED;;GAEG;AACH,SAAgB,QAAQ;IACtB,eAAK,CAAC,UAAU,CAAC,CAAA;AACnB,CAAC;AAFD,4BAEC;AAED;;;;;;;GAOG;AACH,SAAsB,KAAK,CAAI,IAAY,EAAE,EAAoB;;QAC/D,UAAU,CAAC,IAAI,CAAC,CAAA;QAEhB,IAAI,MAAS,CAAA;QAEb,IAAI;YACF,MAAM,GAAG,MAAM,EAAE,EAAE,CAAA;SACpB;gBAAS;YACR,QAAQ,EAAE,CAAA;SACX;QAED,OAAO,MAAM,CAAA;IACf,CAAC;CAAA;AAZD,sBAYC;AAED,yEAAyE;AACzE,uBAAuB;AACvB,yEAAyE;AAEzE;;;;;GAKG;AACH,SAAgB,SAAS,CAAC,IAAY,EAAE,KAAa;IACnD,sBAAY,CAAC,YAAY,EAAE,EAAC,IAAI,EAAC,EAAE,KAAK,CAAC,CAAA;AAC3C,CAAC;AAFD,8BAEC;AAED;;;;;GAKG;AACH,SAAgB,QAAQ,CAAC,IAAY;IACnC,OAAO,OAAO,CAAC,GAAG,CAAC,SAAS,IAAI,EAAE,CAAC,IAAI,EAAE,CAAA;AAC3C,CAAC;AAFD,4BAEC"}
|
||||||
@ -1,7 +0,0 @@
|
|||||||
Copyright 2019 GitHub
|
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
||||||
|
|
||||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
||||||
|
|
||||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
||||||
@ -1,60 +1,57 @@
|
|||||||
# `@actions/exec`
|
# `@actions/exec`
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
#### Basic
|
#### Basic
|
||||||
|
|
||||||
You can use this package to execute your tools on the command line in a cross platform way:
|
You can use this package to execute your tools on the command line in a cross platform way:
|
||||||
|
|
||||||
```
|
```js
|
||||||
const exec = require('@actions/exec');
|
const exec = require('@actions/exec');
|
||||||
|
|
||||||
await exec.exec('node index.js');
|
await exec.exec('node index.js');
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Args
|
#### Args
|
||||||
|
|
||||||
You can also pass in arg arrays:
|
You can also pass in arg arrays:
|
||||||
|
|
||||||
```
|
```js
|
||||||
const exec = require('@actions/exec');
|
const exec = require('@actions/exec');
|
||||||
|
|
||||||
await exec.exec('node', ['index.js', 'foo=bar']);
|
await exec.exec('node', ['index.js', 'foo=bar']);
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Output/options
|
#### Output/options
|
||||||
|
|
||||||
Capture output or specify [other options](https://github.com/actions/toolkit/blob/d9347d4ab99fd507c0b9104b2cf79fb44fcc827d/packages/exec/src/interfaces.ts#L5):
|
Capture output or specify [other options](https://github.com/actions/toolkit/blob/d9347d4ab99fd507c0b9104b2cf79fb44fcc827d/packages/exec/src/interfaces.ts#L5):
|
||||||
|
|
||||||
```
|
```js
|
||||||
const exec = require('@actions/exec');
|
const exec = require('@actions/exec');
|
||||||
|
|
||||||
const myOutput = '';
|
let myOutput = '';
|
||||||
const myError = '';
|
let myError = '';
|
||||||
|
|
||||||
const options = {};
|
const options = {};
|
||||||
options.listeners = {
|
options.listeners = {
|
||||||
stdout: (data: Buffer) => {
|
stdout: (data: Buffer) => {
|
||||||
myOutput += data.toString();
|
myOutput += data.toString();
|
||||||
},
|
},
|
||||||
stderr: (data: Buffer) => {
|
stderr: (data: Buffer) => {
|
||||||
myError += data.toString();
|
myError += data.toString();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
options.cwd = './lib';
|
options.cwd = './lib';
|
||||||
|
|
||||||
await exec.exec('node', ['index.js', 'foo=bar'], options);
|
await exec.exec('node', ['index.js', 'foo=bar'], options);
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Exec tools not in the PATH
|
#### Exec tools not in the PATH
|
||||||
|
|
||||||
You can use it in conjunction with the `which` function from `@actions/io` to execute tools that are not in the PATH:
|
You can specify the full path for tools not in the PATH:
|
||||||
|
|
||||||
```
|
```js
|
||||||
const exec = require('@actions/exec');
|
const exec = require('@actions/exec');
|
||||||
const io = require('@actions/io');
|
|
||||||
|
await exec.exec('"/path/to/my-tool"', ['arg1']);
|
||||||
const pythonPath: string = await io.which('python', true)
|
```
|
||||||
|
|
||||||
await exec.exec(`"${pythonPath}"`, ['main.py']);
|
|
||||||
```
|
|
||||||
|
|||||||
@ -1,12 +1,12 @@
|
|||||||
import * as im from './interfaces';
|
import * as im from './interfaces';
|
||||||
/**
|
/**
|
||||||
* Exec a command.
|
* Exec a command.
|
||||||
* Output will be streamed to the live console.
|
* Output will be streamed to the live console.
|
||||||
* Returns promise with return code
|
* Returns promise with return code
|
||||||
*
|
*
|
||||||
* @param commandLine command to execute (can include additional args). Must be correctly escaped.
|
* @param commandLine command to execute (can include additional args). Must be correctly escaped.
|
||||||
* @param args optional arguments for tool. Escaping is handled by the lib.
|
* @param args optional arguments for tool. Escaping is handled by the lib.
|
||||||
* @param options optional exec options. See ExecOptions
|
* @param options optional exec options. See ExecOptions
|
||||||
* @returns Promise<number> exit code
|
* @returns Promise<number> exit code
|
||||||
*/
|
*/
|
||||||
export declare function exec(commandLine: string, args?: string[], options?: im.ExecOptions): Promise<number>;
|
export declare function exec(commandLine: string, args?: string[], options?: im.ExecOptions): Promise<number>;
|
||||||
|
|||||||
@ -1,36 +1,37 @@
|
|||||||
"use strict";
|
"use strict";
|
||||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||||
return new (P || (P = Promise))(function (resolve, reject) {
|
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
return new (P || (P = Promise))(function (resolve, reject) {
|
||||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||||
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
|
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
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 });
|
};
|
||||||
const tr = require("./toolrunner");
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
/**
|
const tr = require("./toolrunner");
|
||||||
* Exec a command.
|
/**
|
||||||
* Output will be streamed to the live console.
|
* Exec a command.
|
||||||
* Returns promise with return code
|
* Output will be streamed to the live console.
|
||||||
*
|
* Returns promise with return code
|
||||||
* @param commandLine command to execute (can include additional args). Must be correctly escaped.
|
*
|
||||||
* @param args optional arguments for tool. Escaping is handled by the lib.
|
* @param commandLine command to execute (can include additional args). Must be correctly escaped.
|
||||||
* @param options optional exec options. See ExecOptions
|
* @param args optional arguments for tool. Escaping is handled by the lib.
|
||||||
* @returns Promise<number> exit code
|
* @param options optional exec options. See ExecOptions
|
||||||
*/
|
* @returns Promise<number> exit code
|
||||||
function exec(commandLine, args, options) {
|
*/
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
function exec(commandLine, args, options) {
|
||||||
const commandArgs = tr.argStringToArray(commandLine);
|
return __awaiter(this, void 0, void 0, function* () {
|
||||||
if (commandArgs.length === 0) {
|
const commandArgs = tr.argStringToArray(commandLine);
|
||||||
throw new Error(`Parameter 'commandLine' cannot be null or empty.`);
|
if (commandArgs.length === 0) {
|
||||||
}
|
throw new Error(`Parameter 'commandLine' cannot be null or empty.`);
|
||||||
// Path to tool to execute should be first arg
|
}
|
||||||
const toolPath = commandArgs[0];
|
// Path to tool to execute should be first arg
|
||||||
args = commandArgs.slice(1).concat(args || []);
|
const toolPath = commandArgs[0];
|
||||||
const runner = new tr.ToolRunner(toolPath, args, options);
|
args = commandArgs.slice(1).concat(args || []);
|
||||||
return runner.exec();
|
const runner = new tr.ToolRunner(toolPath, args, options);
|
||||||
});
|
return runner.exec();
|
||||||
}
|
});
|
||||||
exports.exec = exec;
|
}
|
||||||
|
exports.exec = exec;
|
||||||
//# sourceMappingURL=exec.js.map
|
//# sourceMappingURL=exec.js.map
|
||||||
@ -1 +1 @@
|
|||||||
{"version":3,"file":"exec.js","sourceRoot":"","sources":["../src/exec.ts"],"names":[],"mappings":";;;;;;;;;;AACA,mCAAkC;AAElC;;;;;;;;;GASG;AACH,SAAsB,IAAI,CACxB,WAAmB,EACnB,IAAe,EACf,OAAwB;;QAExB,M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||||||
/// <reference types="node" />
|
/// <reference types="node" />
|
||||||
import * as stream from 'stream';
|
import * as stream from 'stream';
|
||||||
/**
|
/**
|
||||||
* Interface for exec options
|
* Interface for exec options
|
||||||
*/
|
*/
|
||||||
export interface ExecOptions {
|
export interface ExecOptions {
|
||||||
/** optional working directory. defaults to current */
|
/** optional working directory. defaults to current */
|
||||||
cwd?: string;
|
cwd?: string;
|
||||||
/** optional envvar dictionary. defaults to current process's env */
|
/** optional envvar dictionary. defaults to current process's env */
|
||||||
env?: {
|
env?: {
|
||||||
[key: string]: string;
|
[key: string]: string;
|
||||||
};
|
};
|
||||||
/** optional. defaults to false */
|
/** optional. defaults to false */
|
||||||
silent?: boolean;
|
silent?: boolean;
|
||||||
/** optional out stream to use. Defaults to process.stdout */
|
/** optional out stream to use. Defaults to process.stdout */
|
||||||
outStream?: stream.Writable;
|
outStream?: stream.Writable;
|
||||||
/** optional err stream to use. Defaults to process.stderr */
|
/** optional err stream to use. Defaults to process.stderr */
|
||||||
errStream?: stream.Writable;
|
errStream?: stream.Writable;
|
||||||
/** optional. whether to skip quoting/escaping arguments if needed. defaults to false. */
|
/** optional. whether to skip quoting/escaping arguments if needed. defaults to false. */
|
||||||
windowsVerbatimArguments?: boolean;
|
windowsVerbatimArguments?: boolean;
|
||||||
/** optional. whether to fail if output to stderr. defaults to false */
|
/** optional. whether to fail if output to stderr. defaults to false */
|
||||||
failOnStdErr?: boolean;
|
failOnStdErr?: boolean;
|
||||||
/** optional. defaults to failing on non zero. ignore will not fail leaving it up to the caller */
|
/** optional. defaults to failing on non zero. ignore will not fail leaving it up to the caller */
|
||||||
ignoreReturnCode?: boolean;
|
ignoreReturnCode?: boolean;
|
||||||
/** optional. How long in ms to wait for STDIO streams to close after the exit event of the process before terminating. defaults to 10000 */
|
/** optional. How long in ms to wait for STDIO streams to close after the exit event of the process before terminating. defaults to 10000 */
|
||||||
delay?: number;
|
delay?: number;
|
||||||
/** optional. Listeners for output. Callback functions that will be called on these events */
|
/** optional. Listeners for output. Callback functions that will be called on these events */
|
||||||
listeners?: {
|
listeners?: {
|
||||||
stdout?: (data: Buffer) => void;
|
stdout?: (data: Buffer) => void;
|
||||||
stderr?: (data: Buffer) => void;
|
stderr?: (data: Buffer) => void;
|
||||||
stdline?: (data: string) => void;
|
stdline?: (data: string) => void;
|
||||||
errline?: (data: string) => void;
|
errline?: (data: string) => void;
|
||||||
debug?: (data: string) => void;
|
debug?: (data: string) => void;
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,3 +1,3 @@
|
|||||||
"use strict";
|
"use strict";
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
//# sourceMappingURL=interfaces.js.map
|
//# sourceMappingURL=interfaces.js.map
|
||||||
@ -1,37 +1,37 @@
|
|||||||
/// <reference types="node" />
|
/// <reference types="node" />
|
||||||
import * as events from 'events';
|
import * as events from 'events';
|
||||||
import * as im from './interfaces';
|
import * as im from './interfaces';
|
||||||
export declare class ToolRunner extends events.EventEmitter {
|
export declare class ToolRunner extends events.EventEmitter {
|
||||||
constructor(toolPath: string, args?: string[], options?: im.ExecOptions);
|
constructor(toolPath: string, args?: string[], options?: im.ExecOptions);
|
||||||
private toolPath;
|
private toolPath;
|
||||||
private args;
|
private args;
|
||||||
private options;
|
private options;
|
||||||
private _debug;
|
private _debug;
|
||||||
private _getCommandString;
|
private _getCommandString;
|
||||||
private _processLineBuffer;
|
private _processLineBuffer;
|
||||||
private _getSpawnFileName;
|
private _getSpawnFileName;
|
||||||
private _getSpawnArgs;
|
private _getSpawnArgs;
|
||||||
private _endsWith;
|
private _endsWith;
|
||||||
private _isCmdFile;
|
private _isCmdFile;
|
||||||
private _windowsQuoteCmdArg;
|
private _windowsQuoteCmdArg;
|
||||||
private _uvQuoteCmdArg;
|
private _uvQuoteCmdArg;
|
||||||
private _cloneExecOptions;
|
private _cloneExecOptions;
|
||||||
private _getSpawnOptions;
|
private _getSpawnOptions;
|
||||||
/**
|
/**
|
||||||
* Exec a tool.
|
* Exec a tool.
|
||||||
* Output will be streamed to the live console.
|
* Output will be streamed to the live console.
|
||||||
* Returns promise with return code
|
* Returns promise with return code
|
||||||
*
|
*
|
||||||
* @param tool path to tool to exec
|
* @param tool path to tool to exec
|
||||||
* @param options optional exec options. See ExecOptions
|
* @param options optional exec options. See ExecOptions
|
||||||
* @returns number
|
* @returns number
|
||||||
*/
|
*/
|
||||||
exec(): Promise<number>;
|
exec(): Promise<number>;
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* Convert an arg string to an array of args. Handles escaping
|
* Convert an arg string to an array of args. Handles escaping
|
||||||
*
|
*
|
||||||
* @param argString string of arguments
|
* @param argString string of arguments
|
||||||
* @returns string[] array of arguments
|
* @returns string[] array of arguments
|
||||||
*/
|
*/
|
||||||
export declare function argStringToArray(argString: string): string[];
|
export declare function argStringToArray(argString: string): string[];
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
@ -1,7 +1,7 @@
|
|||||||
Copyright 2019 GitHub
|
Copyright 2019 GitHub
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||||
|
|
||||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||||
@ -1,53 +1,53 @@
|
|||||||
# `@actions/io`
|
# `@actions/io`
|
||||||
|
|
||||||
> Core functions for cli filesystem scenarios
|
> Core functions for cli filesystem scenarios
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
#### mkdir -p
|
#### mkdir -p
|
||||||
|
|
||||||
Recursively make a directory. Follows rules specified in [man mkdir](https://linux.die.net/man/1/mkdir) with the `-p` option specified:
|
Recursively make a directory. Follows rules specified in [man mkdir](https://linux.die.net/man/1/mkdir) with the `-p` option specified:
|
||||||
|
|
||||||
```
|
```js
|
||||||
const io = require('@actions/io');
|
const io = require('@actions/io');
|
||||||
|
|
||||||
await io.mkdirP('path/to/make');
|
await io.mkdirP('path/to/make');
|
||||||
```
|
```
|
||||||
|
|
||||||
#### cp/mv
|
#### cp/mv
|
||||||
|
|
||||||
Copy or move files or folders. Follows rules specified in [man cp](https://linux.die.net/man/1/cp) and [man mv](https://linux.die.net/man/1/mv):
|
Copy or move files or folders. Follows rules specified in [man cp](https://linux.die.net/man/1/cp) and [man mv](https://linux.die.net/man/1/mv):
|
||||||
|
|
||||||
```
|
```js
|
||||||
const io = require('@actions/io');
|
const io = require('@actions/io');
|
||||||
|
|
||||||
// Recursive must be true for directories
|
// Recursive must be true for directories
|
||||||
const options = { recursive: true, force: false }
|
const options = { recursive: true, force: false }
|
||||||
|
|
||||||
await io.cp('path/to/directory', 'path/to/dest', options);
|
await io.cp('path/to/directory', 'path/to/dest', options);
|
||||||
await io.mv('path/to/file', 'path/to/dest');
|
await io.mv('path/to/file', 'path/to/dest');
|
||||||
```
|
```
|
||||||
|
|
||||||
#### rm -rf
|
#### rm -rf
|
||||||
|
|
||||||
Remove a file or folder recursively. Follows rules specified in [man rm](https://linux.die.net/man/1/rm) with the `-r` and `-f` rules specified.
|
Remove a file or folder recursively. Follows rules specified in [man rm](https://linux.die.net/man/1/rm) with the `-r` and `-f` rules specified.
|
||||||
|
|
||||||
```
|
```js
|
||||||
const io = require('@actions/io');
|
const io = require('@actions/io');
|
||||||
|
|
||||||
await io.rmRF('path/to/directory');
|
await io.rmRF('path/to/directory');
|
||||||
await io.rmRF('path/to/file');
|
await io.rmRF('path/to/file');
|
||||||
```
|
```
|
||||||
|
|
||||||
#### which
|
#### which
|
||||||
|
|
||||||
Get the path to a tool and resolves via paths. Follows the rules specified in [man which](https://linux.die.net/man/1/which).
|
Get the path to a tool and resolves via paths. Follows the rules specified in [man which](https://linux.die.net/man/1/which).
|
||||||
|
|
||||||
```
|
```js
|
||||||
const exec = require('@actions/exec');
|
const exec = require('@actions/exec');
|
||||||
const io = require('@actions/io');
|
const io = require('@actions/io');
|
||||||
|
|
||||||
const pythonPath: string = await io.which('python', true)
|
const pythonPath: string = await io.which('python', true)
|
||||||
|
|
||||||
await exec.exec(`"${pythonPath}"`, ['main.py']);
|
await exec.exec(`"${pythonPath}"`, ['main.py']);
|
||||||
```
|
```
|
||||||
|
|||||||
@ -1,29 +1,29 @@
|
|||||||
/// <reference types="node" />
|
/// <reference types="node" />
|
||||||
import * as fs from 'fs';
|
import * as fs from 'fs';
|
||||||
export declare const chmod: typeof fs.promises.chmod, copyFile: typeof fs.promises.copyFile, lstat: typeof fs.promises.lstat, mkdir: typeof fs.promises.mkdir, readdir: typeof fs.promises.readdir, readlink: typeof fs.promises.readlink, rename: typeof fs.promises.rename, rmdir: typeof fs.promises.rmdir, stat: typeof fs.promises.stat, symlink: typeof fs.promises.symlink, unlink: typeof fs.promises.unlink;
|
export declare const chmod: typeof fs.promises.chmod, copyFile: typeof fs.promises.copyFile, lstat: typeof fs.promises.lstat, mkdir: typeof fs.promises.mkdir, readdir: typeof fs.promises.readdir, readlink: typeof fs.promises.readlink, rename: typeof fs.promises.rename, rmdir: typeof fs.promises.rmdir, stat: typeof fs.promises.stat, symlink: typeof fs.promises.symlink, unlink: typeof fs.promises.unlink;
|
||||||
export declare const IS_WINDOWS: boolean;
|
export declare const IS_WINDOWS: boolean;
|
||||||
export declare function exists(fsPath: string): Promise<boolean>;
|
export declare function exists(fsPath: string): Promise<boolean>;
|
||||||
export declare function isDirectory(fsPath: string, useStat?: boolean): Promise<boolean>;
|
export declare function isDirectory(fsPath: string, useStat?: boolean): Promise<boolean>;
|
||||||
/**
|
/**
|
||||||
* On OSX/Linux, true if path starts with '/'. On Windows, true for paths like:
|
* On OSX/Linux, true if path starts with '/'. On Windows, true for paths like:
|
||||||
* \, \hello, \\hello\share, C:, and C:\hello (and corresponding alternate separator cases).
|
* \, \hello, \\hello\share, C:, and C:\hello (and corresponding alternate separator cases).
|
||||||
*/
|
*/
|
||||||
export declare function isRooted(p: string): boolean;
|
export declare function isRooted(p: string): boolean;
|
||||||
/**
|
/**
|
||||||
* Recursively create a directory at `fsPath`.
|
* Recursively create a directory at `fsPath`.
|
||||||
*
|
*
|
||||||
* This implementation is optimistic, meaning it attempts to create the full
|
* This implementation is optimistic, meaning it attempts to create the full
|
||||||
* path first, and backs up the path stack from there.
|
* path first, and backs up the path stack from there.
|
||||||
*
|
*
|
||||||
* @param fsPath The path to create
|
* @param fsPath The path to create
|
||||||
* @param maxDepth The maximum recursion depth
|
* @param maxDepth The maximum recursion depth
|
||||||
* @param depth The current recursion depth
|
* @param depth The current recursion depth
|
||||||
*/
|
*/
|
||||||
export declare function mkdirP(fsPath: string, maxDepth?: number, depth?: number): Promise<void>;
|
export declare function mkdirP(fsPath: string, maxDepth?: number, depth?: number): Promise<void>;
|
||||||
/**
|
/**
|
||||||
* Best effort attempt to determine whether a file exists and is executable.
|
* Best effort attempt to determine whether a file exists and is executable.
|
||||||
* @param filePath file path to check
|
* @param filePath file path to check
|
||||||
* @param extensions additional file extensions to try
|
* @param extensions additional file extensions to try
|
||||||
* @return if file exists and is executable, returns the file path. otherwise empty string.
|
* @return if file exists and is executable, returns the file path. otherwise empty string.
|
||||||
*/
|
*/
|
||||||
export declare function tryGetExecutablePath(filePath: string, extensions: string[]): Promise<string>;
|
export declare function tryGetExecutablePath(filePath: string, extensions: string[]): Promise<string>;
|
||||||
|
|||||||
@ -1,194 +1,195 @@
|
|||||||
"use strict";
|
"use strict";
|
||||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||||
return new (P || (P = Promise))(function (resolve, reject) {
|
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
return new (P || (P = Promise))(function (resolve, reject) {
|
||||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||||
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
|
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||||
});
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||||
};
|
});
|
||||||
var _a;
|
};
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
var _a;
|
||||||
const assert_1 = require("assert");
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
const fs = require("fs");
|
const assert_1 = require("assert");
|
||||||
const path = require("path");
|
const fs = require("fs");
|
||||||
_a = fs.promises, exports.chmod = _a.chmod, exports.copyFile = _a.copyFile, exports.lstat = _a.lstat, exports.mkdir = _a.mkdir, exports.readdir = _a.readdir, exports.readlink = _a.readlink, exports.rename = _a.rename, exports.rmdir = _a.rmdir, exports.stat = _a.stat, exports.symlink = _a.symlink, exports.unlink = _a.unlink;
|
const path = require("path");
|
||||||
exports.IS_WINDOWS = process.platform === 'win32';
|
_a = fs.promises, exports.chmod = _a.chmod, exports.copyFile = _a.copyFile, exports.lstat = _a.lstat, exports.mkdir = _a.mkdir, exports.readdir = _a.readdir, exports.readlink = _a.readlink, exports.rename = _a.rename, exports.rmdir = _a.rmdir, exports.stat = _a.stat, exports.symlink = _a.symlink, exports.unlink = _a.unlink;
|
||||||
function exists(fsPath) {
|
exports.IS_WINDOWS = process.platform === 'win32';
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
function exists(fsPath) {
|
||||||
try {
|
return __awaiter(this, void 0, void 0, function* () {
|
||||||
yield exports.stat(fsPath);
|
try {
|
||||||
}
|
yield exports.stat(fsPath);
|
||||||
catch (err) {
|
}
|
||||||
if (err.code === 'ENOENT') {
|
catch (err) {
|
||||||
return false;
|
if (err.code === 'ENOENT') {
|
||||||
}
|
return false;
|
||||||
throw err;
|
}
|
||||||
}
|
throw err;
|
||||||
return true;
|
}
|
||||||
});
|
return true;
|
||||||
}
|
});
|
||||||
exports.exists = exists;
|
}
|
||||||
function isDirectory(fsPath, useStat = false) {
|
exports.exists = exists;
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
function isDirectory(fsPath, useStat = false) {
|
||||||
const stats = useStat ? yield exports.stat(fsPath) : yield exports.lstat(fsPath);
|
return __awaiter(this, void 0, void 0, function* () {
|
||||||
return stats.isDirectory();
|
const stats = useStat ? yield exports.stat(fsPath) : yield exports.lstat(fsPath);
|
||||||
});
|
return stats.isDirectory();
|
||||||
}
|
});
|
||||||
exports.isDirectory = isDirectory;
|
}
|
||||||
/**
|
exports.isDirectory = isDirectory;
|
||||||
* On OSX/Linux, true if path starts with '/'. On Windows, true for paths like:
|
/**
|
||||||
* \, \hello, \\hello\share, C:, and C:\hello (and corresponding alternate separator cases).
|
* On OSX/Linux, true if path starts with '/'. On Windows, true for paths like:
|
||||||
*/
|
* \, \hello, \\hello\share, C:, and C:\hello (and corresponding alternate separator cases).
|
||||||
function isRooted(p) {
|
*/
|
||||||
p = normalizeSeparators(p);
|
function isRooted(p) {
|
||||||
if (!p) {
|
p = normalizeSeparators(p);
|
||||||
throw new Error('isRooted() parameter "p" cannot be empty');
|
if (!p) {
|
||||||
}
|
throw new Error('isRooted() parameter "p" cannot be empty');
|
||||||
if (exports.IS_WINDOWS) {
|
}
|
||||||
return (p.startsWith('\\') || /^[A-Z]:/i.test(p) // e.g. \ or \hello or \\hello
|
if (exports.IS_WINDOWS) {
|
||||||
); // e.g. C: or C:\hello
|
return (p.startsWith('\\') || /^[A-Z]:/i.test(p) // e.g. \ or \hello or \\hello
|
||||||
}
|
); // e.g. C: or C:\hello
|
||||||
return p.startsWith('/');
|
}
|
||||||
}
|
return p.startsWith('/');
|
||||||
exports.isRooted = isRooted;
|
}
|
||||||
/**
|
exports.isRooted = isRooted;
|
||||||
* Recursively create a directory at `fsPath`.
|
/**
|
||||||
*
|
* Recursively create a directory at `fsPath`.
|
||||||
* This implementation is optimistic, meaning it attempts to create the full
|
*
|
||||||
* path first, and backs up the path stack from there.
|
* This implementation is optimistic, meaning it attempts to create the full
|
||||||
*
|
* path first, and backs up the path stack from there.
|
||||||
* @param fsPath The path to create
|
*
|
||||||
* @param maxDepth The maximum recursion depth
|
* @param fsPath The path to create
|
||||||
* @param depth The current recursion depth
|
* @param maxDepth The maximum recursion depth
|
||||||
*/
|
* @param depth The current recursion depth
|
||||||
function mkdirP(fsPath, maxDepth = 1000, depth = 1) {
|
*/
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
function mkdirP(fsPath, maxDepth = 1000, depth = 1) {
|
||||||
assert_1.ok(fsPath, 'a path argument must be provided');
|
return __awaiter(this, void 0, void 0, function* () {
|
||||||
fsPath = path.resolve(fsPath);
|
assert_1.ok(fsPath, 'a path argument must be provided');
|
||||||
if (depth >= maxDepth)
|
fsPath = path.resolve(fsPath);
|
||||||
return exports.mkdir(fsPath);
|
if (depth >= maxDepth)
|
||||||
try {
|
return exports.mkdir(fsPath);
|
||||||
yield exports.mkdir(fsPath);
|
try {
|
||||||
return;
|
yield exports.mkdir(fsPath);
|
||||||
}
|
return;
|
||||||
catch (err) {
|
}
|
||||||
switch (err.code) {
|
catch (err) {
|
||||||
case 'ENOENT': {
|
switch (err.code) {
|
||||||
yield mkdirP(path.dirname(fsPath), maxDepth, depth + 1);
|
case 'ENOENT': {
|
||||||
yield exports.mkdir(fsPath);
|
yield mkdirP(path.dirname(fsPath), maxDepth, depth + 1);
|
||||||
return;
|
yield exports.mkdir(fsPath);
|
||||||
}
|
return;
|
||||||
default: {
|
}
|
||||||
let stats;
|
default: {
|
||||||
try {
|
let stats;
|
||||||
stats = yield exports.stat(fsPath);
|
try {
|
||||||
}
|
stats = yield exports.stat(fsPath);
|
||||||
catch (err2) {
|
}
|
||||||
throw err;
|
catch (err2) {
|
||||||
}
|
throw err;
|
||||||
if (!stats.isDirectory())
|
}
|
||||||
throw err;
|
if (!stats.isDirectory())
|
||||||
}
|
throw err;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
}
|
||||||
}
|
});
|
||||||
exports.mkdirP = mkdirP;
|
}
|
||||||
/**
|
exports.mkdirP = mkdirP;
|
||||||
* Best effort attempt to determine whether a file exists and is executable.
|
/**
|
||||||
* @param filePath file path to check
|
* Best effort attempt to determine whether a file exists and is executable.
|
||||||
* @param extensions additional file extensions to try
|
* @param filePath file path to check
|
||||||
* @return if file exists and is executable, returns the file path. otherwise empty string.
|
* @param extensions additional file extensions to try
|
||||||
*/
|
* @return if file exists and is executable, returns the file path. otherwise empty string.
|
||||||
function tryGetExecutablePath(filePath, extensions) {
|
*/
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
function tryGetExecutablePath(filePath, extensions) {
|
||||||
let stats = undefined;
|
return __awaiter(this, void 0, void 0, function* () {
|
||||||
try {
|
let stats = undefined;
|
||||||
// test file exists
|
try {
|
||||||
stats = yield exports.stat(filePath);
|
// test file exists
|
||||||
}
|
stats = yield exports.stat(filePath);
|
||||||
catch (err) {
|
}
|
||||||
if (err.code !== 'ENOENT') {
|
catch (err) {
|
||||||
// eslint-disable-next-line no-console
|
if (err.code !== 'ENOENT') {
|
||||||
console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`);
|
// eslint-disable-next-line no-console
|
||||||
}
|
console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`);
|
||||||
}
|
}
|
||||||
if (stats && stats.isFile()) {
|
}
|
||||||
if (exports.IS_WINDOWS) {
|
if (stats && stats.isFile()) {
|
||||||
// on Windows, test for valid extension
|
if (exports.IS_WINDOWS) {
|
||||||
const upperExt = path.extname(filePath).toUpperCase();
|
// on Windows, test for valid extension
|
||||||
if (extensions.some(validExt => validExt.toUpperCase() === upperExt)) {
|
const upperExt = path.extname(filePath).toUpperCase();
|
||||||
return filePath;
|
if (extensions.some(validExt => validExt.toUpperCase() === upperExt)) {
|
||||||
}
|
return filePath;
|
||||||
}
|
}
|
||||||
else {
|
}
|
||||||
if (isUnixExecutable(stats)) {
|
else {
|
||||||
return filePath;
|
if (isUnixExecutable(stats)) {
|
||||||
}
|
return filePath;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// try each extension
|
}
|
||||||
const originalFilePath = filePath;
|
// try each extension
|
||||||
for (const extension of extensions) {
|
const originalFilePath = filePath;
|
||||||
filePath = originalFilePath + extension;
|
for (const extension of extensions) {
|
||||||
stats = undefined;
|
filePath = originalFilePath + extension;
|
||||||
try {
|
stats = undefined;
|
||||||
stats = yield exports.stat(filePath);
|
try {
|
||||||
}
|
stats = yield exports.stat(filePath);
|
||||||
catch (err) {
|
}
|
||||||
if (err.code !== 'ENOENT') {
|
catch (err) {
|
||||||
// eslint-disable-next-line no-console
|
if (err.code !== 'ENOENT') {
|
||||||
console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`);
|
// eslint-disable-next-line no-console
|
||||||
}
|
console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`);
|
||||||
}
|
}
|
||||||
if (stats && stats.isFile()) {
|
}
|
||||||
if (exports.IS_WINDOWS) {
|
if (stats && stats.isFile()) {
|
||||||
// preserve the case of the actual file (since an extension was appended)
|
if (exports.IS_WINDOWS) {
|
||||||
try {
|
// preserve the case of the actual file (since an extension was appended)
|
||||||
const directory = path.dirname(filePath);
|
try {
|
||||||
const upperName = path.basename(filePath).toUpperCase();
|
const directory = path.dirname(filePath);
|
||||||
for (const actualName of yield exports.readdir(directory)) {
|
const upperName = path.basename(filePath).toUpperCase();
|
||||||
if (upperName === actualName.toUpperCase()) {
|
for (const actualName of yield exports.readdir(directory)) {
|
||||||
filePath = path.join(directory, actualName);
|
if (upperName === actualName.toUpperCase()) {
|
||||||
break;
|
filePath = path.join(directory, actualName);
|
||||||
}
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch (err) {
|
}
|
||||||
// eslint-disable-next-line no-console
|
catch (err) {
|
||||||
console.log(`Unexpected error attempting to determine the actual case of the file '${filePath}': ${err}`);
|
// eslint-disable-next-line no-console
|
||||||
}
|
console.log(`Unexpected error attempting to determine the actual case of the file '${filePath}': ${err}`);
|
||||||
return filePath;
|
}
|
||||||
}
|
return filePath;
|
||||||
else {
|
}
|
||||||
if (isUnixExecutable(stats)) {
|
else {
|
||||||
return filePath;
|
if (isUnixExecutable(stats)) {
|
||||||
}
|
return filePath;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return '';
|
}
|
||||||
});
|
return '';
|
||||||
}
|
});
|
||||||
exports.tryGetExecutablePath = tryGetExecutablePath;
|
}
|
||||||
function normalizeSeparators(p) {
|
exports.tryGetExecutablePath = tryGetExecutablePath;
|
||||||
p = p || '';
|
function normalizeSeparators(p) {
|
||||||
if (exports.IS_WINDOWS) {
|
p = p || '';
|
||||||
// convert slashes on Windows
|
if (exports.IS_WINDOWS) {
|
||||||
p = p.replace(/\//g, '\\');
|
// convert slashes on Windows
|
||||||
// remove redundant slashes
|
p = p.replace(/\//g, '\\');
|
||||||
return p.replace(/\\\\+/g, '\\');
|
// remove redundant slashes
|
||||||
}
|
return p.replace(/\\\\+/g, '\\');
|
||||||
// remove redundant slashes
|
}
|
||||||
return p.replace(/\/\/+/g, '/');
|
// remove redundant slashes
|
||||||
}
|
return p.replace(/\/\/+/g, '/');
|
||||||
// on Mac/Linux, test the execute bit
|
}
|
||||||
// R W X R W X R W X
|
// on Mac/Linux, test the execute bit
|
||||||
// 256 128 64 32 16 8 4 2 1
|
// R W X R W X R W X
|
||||||
function isUnixExecutable(stats) {
|
// 256 128 64 32 16 8 4 2 1
|
||||||
return ((stats.mode & 1) > 0 ||
|
function isUnixExecutable(stats) {
|
||||||
((stats.mode & 8) > 0 && stats.gid === process.getgid()) ||
|
return ((stats.mode & 1) > 0 ||
|
||||||
((stats.mode & 64) > 0 && stats.uid === process.getuid()));
|
((stats.mode & 8) > 0 && stats.gid === process.getgid()) ||
|
||||||
}
|
((stats.mode & 64) > 0 && stats.uid === process.getuid()));
|
||||||
|
}
|
||||||
//# sourceMappingURL=io-util.js.map
|
//# sourceMappingURL=io-util.js.map
|
||||||
@ -1 +1 @@
|
|||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mv options
|
* Interface for cp/mv options
|
||||||
*/
|
*/
|
||||||
export interface CopyOptions {
|
export interface CopyOptions {
|
||||||
/** Optional. Whether to recursively copy all subdirectories. Defaults to false */
|
/** Optional. Whether to recursively copy all subdirectories. Defaults to false */
|
||||||
recursive?: boolean;
|
recursive?: boolean;
|
||||||
/** Optional. Whether to overwrite existing files in the destination. Defaults to true */
|
/** Optional. Whether to overwrite existing files in the destination. Defaults to true */
|
||||||
force?: boolean;
|
force?: boolean;
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* Interface for cp/mv options
|
* Interface for cp/mv options
|
||||||
*/
|
*/
|
||||||
export interface MoveOptions {
|
export interface MoveOptions {
|
||||||
/** Optional. Whether to overwrite existing files in the destination. Defaults to true */
|
/** Optional. Whether to overwrite existing files in the destination. Defaults to true */
|
||||||
force?: boolean;
|
force?: boolean;
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* Copies a file or folder.
|
* Copies a file or folder.
|
||||||
* Based off of shelljs - https://github.com/shelljs/shelljs/blob/9237f66c52e5daa40458f94f9565e18e8132f5a6/src/cp.js
|
* Based off of shelljs - https://github.com/shelljs/shelljs/blob/9237f66c52e5daa40458f94f9565e18e8132f5a6/src/cp.js
|
||||||
*
|
*
|
||||||
* @param source source path
|
* @param source source path
|
||||||
* @param dest destination path
|
* @param dest destination path
|
||||||
* @param options optional. See CopyOptions.
|
* @param options optional. See CopyOptions.
|
||||||
*/
|
*/
|
||||||
export declare function cp(source: string, dest: string, options?: CopyOptions): Promise<void>;
|
export declare function cp(source: string, dest: string, options?: CopyOptions): Promise<void>;
|
||||||
/**
|
/**
|
||||||
* Moves a path.
|
* Moves a path.
|
||||||
*
|
*
|
||||||
* @param source source path
|
* @param source source path
|
||||||
* @param dest destination path
|
* @param dest destination path
|
||||||
* @param options optional. See MoveOptions.
|
* @param options optional. See MoveOptions.
|
||||||
*/
|
*/
|
||||||
export declare function mv(source: string, dest: string, options?: MoveOptions): Promise<void>;
|
export declare function mv(source: string, dest: string, options?: MoveOptions): Promise<void>;
|
||||||
/**
|
/**
|
||||||
* Remove a path recursively with force
|
* Remove a path recursively with force
|
||||||
*
|
*
|
||||||
* @param inputPath path to remove
|
* @param inputPath path to remove
|
||||||
*/
|
*/
|
||||||
export declare function rmRF(inputPath: string): Promise<void>;
|
export declare function rmRF(inputPath: string): Promise<void>;
|
||||||
/**
|
/**
|
||||||
* Make a directory. Creates the full path with folders in between
|
* Make a directory. Creates the full path with folders in between
|
||||||
* Will throw if it fails
|
* Will throw if it fails
|
||||||
*
|
*
|
||||||
* @param fsPath path to create
|
* @param fsPath path to create
|
||||||
* @returns Promise<void>
|
* @returns Promise<void>
|
||||||
*/
|
*/
|
||||||
export declare function mkdirP(fsPath: string): Promise<void>;
|
export declare function mkdirP(fsPath: string): Promise<void>;
|
||||||
/**
|
/**
|
||||||
* Returns path of a tool had the tool actually been invoked. Resolves via paths.
|
* Returns path of a tool had the tool actually been invoked. Resolves via paths.
|
||||||
* If you check and the tool does not exist, it will throw.
|
* If you check and the tool does not exist, it will throw.
|
||||||
*
|
*
|
||||||
* @param tool name of the tool
|
* @param tool name of the tool
|
||||||
* @param check whether to check if tool exists
|
* @param check whether to check if tool exists
|
||||||
* @returns Promise<string> path to tool
|
* @returns Promise<string> path to tool
|
||||||
*/
|
*/
|
||||||
export declare function which(tool: string, check?: boolean): Promise<string>;
|
export declare function which(tool: string, check?: boolean): Promise<string>;
|
||||||
|
|||||||
@ -1,289 +1,290 @@
|
|||||||
"use strict";
|
"use strict";
|
||||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||||
return new (P || (P = Promise))(function (resolve, reject) {
|
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
return new (P || (P = Promise))(function (resolve, reject) {
|
||||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||||
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
|
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
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 });
|
};
|
||||||
const childProcess = require("child_process");
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
const path = require("path");
|
const childProcess = require("child_process");
|
||||||
const util_1 = require("util");
|
const path = require("path");
|
||||||
const ioUtil = require("./io-util");
|
const util_1 = require("util");
|
||||||
const exec = util_1.promisify(childProcess.exec);
|
const ioUtil = require("./io-util");
|
||||||
/**
|
const exec = util_1.promisify(childProcess.exec);
|
||||||
* Copies a file or folder.
|
/**
|
||||||
* Based off of shelljs - https://github.com/shelljs/shelljs/blob/9237f66c52e5daa40458f94f9565e18e8132f5a6/src/cp.js
|
* Copies a file or folder.
|
||||||
*
|
* Based off of shelljs - https://github.com/shelljs/shelljs/blob/9237f66c52e5daa40458f94f9565e18e8132f5a6/src/cp.js
|
||||||
* @param source source path
|
*
|
||||||
* @param dest destination path
|
* @param source source path
|
||||||
* @param options optional. See CopyOptions.
|
* @param dest destination path
|
||||||
*/
|
* @param options optional. See CopyOptions.
|
||||||
function cp(source, dest, options = {}) {
|
*/
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
function cp(source, dest, options = {}) {
|
||||||
const { force, recursive } = readCopyOptions(options);
|
return __awaiter(this, void 0, void 0, function* () {
|
||||||
const destStat = (yield ioUtil.exists(dest)) ? yield ioUtil.stat(dest) : null;
|
const { force, recursive } = readCopyOptions(options);
|
||||||
// Dest is an existing file, but not forcing
|
const destStat = (yield ioUtil.exists(dest)) ? yield ioUtil.stat(dest) : null;
|
||||||
if (destStat && destStat.isFile() && !force) {
|
// Dest is an existing file, but not forcing
|
||||||
return;
|
if (destStat && destStat.isFile() && !force) {
|
||||||
}
|
return;
|
||||||
// If dest is an existing directory, should copy inside.
|
}
|
||||||
const newDest = destStat && destStat.isDirectory()
|
// If dest is an existing directory, should copy inside.
|
||||||
? path.join(dest, path.basename(source))
|
const newDest = destStat && destStat.isDirectory()
|
||||||
: dest;
|
? path.join(dest, path.basename(source))
|
||||||
if (!(yield ioUtil.exists(source))) {
|
: dest;
|
||||||
throw new Error(`no such file or directory: ${source}`);
|
if (!(yield ioUtil.exists(source))) {
|
||||||
}
|
throw new Error(`no such file or directory: ${source}`);
|
||||||
const sourceStat = yield ioUtil.stat(source);
|
}
|
||||||
if (sourceStat.isDirectory()) {
|
const sourceStat = yield ioUtil.stat(source);
|
||||||
if (!recursive) {
|
if (sourceStat.isDirectory()) {
|
||||||
throw new Error(`Failed to copy. ${source} is a directory, but tried to copy without recursive flag.`);
|
if (!recursive) {
|
||||||
}
|
throw new Error(`Failed to copy. ${source} is a directory, but tried to copy without recursive flag.`);
|
||||||
else {
|
}
|
||||||
yield cpDirRecursive(source, newDest, 0, force);
|
else {
|
||||||
}
|
yield cpDirRecursive(source, newDest, 0, force);
|
||||||
}
|
}
|
||||||
else {
|
}
|
||||||
if (path.relative(source, newDest) === '') {
|
else {
|
||||||
// a file cannot be copied to itself
|
if (path.relative(source, newDest) === '') {
|
||||||
throw new Error(`'${newDest}' and '${source}' are the same file`);
|
// a file cannot be copied to itself
|
||||||
}
|
throw new Error(`'${newDest}' and '${source}' are the same file`);
|
||||||
yield copyFile(source, newDest, force);
|
}
|
||||||
}
|
yield copyFile(source, newDest, force);
|
||||||
});
|
}
|
||||||
}
|
});
|
||||||
exports.cp = cp;
|
}
|
||||||
/**
|
exports.cp = cp;
|
||||||
* Moves a path.
|
/**
|
||||||
*
|
* Moves a path.
|
||||||
* @param source source path
|
*
|
||||||
* @param dest destination path
|
* @param source source path
|
||||||
* @param options optional. See MoveOptions.
|
* @param dest destination path
|
||||||
*/
|
* @param options optional. See MoveOptions.
|
||||||
function mv(source, dest, options = {}) {
|
*/
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
function mv(source, dest, options = {}) {
|
||||||
if (yield ioUtil.exists(dest)) {
|
return __awaiter(this, void 0, void 0, function* () {
|
||||||
let destExists = true;
|
if (yield ioUtil.exists(dest)) {
|
||||||
if (yield ioUtil.isDirectory(dest)) {
|
let destExists = true;
|
||||||
// If dest is directory copy src into dest
|
if (yield ioUtil.isDirectory(dest)) {
|
||||||
dest = path.join(dest, path.basename(source));
|
// If dest is directory copy src into dest
|
||||||
destExists = yield ioUtil.exists(dest);
|
dest = path.join(dest, path.basename(source));
|
||||||
}
|
destExists = yield ioUtil.exists(dest);
|
||||||
if (destExists) {
|
}
|
||||||
if (options.force == null || options.force) {
|
if (destExists) {
|
||||||
yield rmRF(dest);
|
if (options.force == null || options.force) {
|
||||||
}
|
yield rmRF(dest);
|
||||||
else {
|
}
|
||||||
throw new Error('Destination already exists');
|
else {
|
||||||
}
|
throw new Error('Destination already exists');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
yield mkdirP(path.dirname(dest));
|
}
|
||||||
yield ioUtil.rename(source, dest);
|
yield mkdirP(path.dirname(dest));
|
||||||
});
|
yield ioUtil.rename(source, dest);
|
||||||
}
|
});
|
||||||
exports.mv = mv;
|
}
|
||||||
/**
|
exports.mv = mv;
|
||||||
* Remove a path recursively with force
|
/**
|
||||||
*
|
* Remove a path recursively with force
|
||||||
* @param inputPath path to remove
|
*
|
||||||
*/
|
* @param inputPath path to remove
|
||||||
function rmRF(inputPath) {
|
*/
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
function rmRF(inputPath) {
|
||||||
if (ioUtil.IS_WINDOWS) {
|
return __awaiter(this, void 0, void 0, function* () {
|
||||||
// Node doesn't provide a delete operation, only an unlink function. This means that if the file is being used by another
|
if (ioUtil.IS_WINDOWS) {
|
||||||
// program (e.g. antivirus), it won't be deleted. To address this, we shell out the work to rd/del.
|
// Node doesn't provide a delete operation, only an unlink function. This means that if the file is being used by another
|
||||||
try {
|
// program (e.g. antivirus), it won't be deleted. To address this, we shell out the work to rd/del.
|
||||||
if (yield ioUtil.isDirectory(inputPath, true)) {
|
try {
|
||||||
yield exec(`rd /s /q "${inputPath}"`);
|
if (yield ioUtil.isDirectory(inputPath, true)) {
|
||||||
}
|
yield exec(`rd /s /q "${inputPath}"`);
|
||||||
else {
|
}
|
||||||
yield exec(`del /f /a "${inputPath}"`);
|
else {
|
||||||
}
|
yield exec(`del /f /a "${inputPath}"`);
|
||||||
}
|
}
|
||||||
catch (err) {
|
}
|
||||||
// if you try to delete a file that doesn't exist, desired result is achieved
|
catch (err) {
|
||||||
// other errors are valid
|
// if you try to delete a file that doesn't exist, desired result is achieved
|
||||||
if (err.code !== 'ENOENT')
|
// other errors are valid
|
||||||
throw err;
|
if (err.code !== 'ENOENT')
|
||||||
}
|
throw err;
|
||||||
// Shelling out fails to remove a symlink folder with missing source, this unlink catches that
|
}
|
||||||
try {
|
// Shelling out fails to remove a symlink folder with missing source, this unlink catches that
|
||||||
yield ioUtil.unlink(inputPath);
|
try {
|
||||||
}
|
yield ioUtil.unlink(inputPath);
|
||||||
catch (err) {
|
}
|
||||||
// if you try to delete a file that doesn't exist, desired result is achieved
|
catch (err) {
|
||||||
// other errors are valid
|
// if you try to delete a file that doesn't exist, desired result is achieved
|
||||||
if (err.code !== 'ENOENT')
|
// other errors are valid
|
||||||
throw err;
|
if (err.code !== 'ENOENT')
|
||||||
}
|
throw err;
|
||||||
}
|
}
|
||||||
else {
|
}
|
||||||
let isDir = false;
|
else {
|
||||||
try {
|
let isDir = false;
|
||||||
isDir = yield ioUtil.isDirectory(inputPath);
|
try {
|
||||||
}
|
isDir = yield ioUtil.isDirectory(inputPath);
|
||||||
catch (err) {
|
}
|
||||||
// if you try to delete a file that doesn't exist, desired result is achieved
|
catch (err) {
|
||||||
// other errors are valid
|
// if you try to delete a file that doesn't exist, desired result is achieved
|
||||||
if (err.code !== 'ENOENT')
|
// other errors are valid
|
||||||
throw err;
|
if (err.code !== 'ENOENT')
|
||||||
return;
|
throw err;
|
||||||
}
|
return;
|
||||||
if (isDir) {
|
}
|
||||||
yield exec(`rm -rf "${inputPath}"`);
|
if (isDir) {
|
||||||
}
|
yield exec(`rm -rf "${inputPath}"`);
|
||||||
else {
|
}
|
||||||
yield ioUtil.unlink(inputPath);
|
else {
|
||||||
}
|
yield ioUtil.unlink(inputPath);
|
||||||
}
|
}
|
||||||
});
|
}
|
||||||
}
|
});
|
||||||
exports.rmRF = rmRF;
|
}
|
||||||
/**
|
exports.rmRF = rmRF;
|
||||||
* Make a directory. Creates the full path with folders in between
|
/**
|
||||||
* Will throw if it fails
|
* Make a directory. Creates the full path with folders in between
|
||||||
*
|
* Will throw if it fails
|
||||||
* @param fsPath path to create
|
*
|
||||||
* @returns Promise<void>
|
* @param fsPath path to create
|
||||||
*/
|
* @returns Promise<void>
|
||||||
function mkdirP(fsPath) {
|
*/
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
function mkdirP(fsPath) {
|
||||||
yield ioUtil.mkdirP(fsPath);
|
return __awaiter(this, void 0, void 0, function* () {
|
||||||
});
|
yield ioUtil.mkdirP(fsPath);
|
||||||
}
|
});
|
||||||
exports.mkdirP = mkdirP;
|
}
|
||||||
/**
|
exports.mkdirP = mkdirP;
|
||||||
* Returns path of a tool had the tool actually been invoked. Resolves via paths.
|
/**
|
||||||
* If you check and the tool does not exist, it will throw.
|
* Returns path of a tool had the tool actually been invoked. Resolves via paths.
|
||||||
*
|
* If you check and the tool does not exist, it will throw.
|
||||||
* @param tool name of the tool
|
*
|
||||||
* @param check whether to check if tool exists
|
* @param tool name of the tool
|
||||||
* @returns Promise<string> path to tool
|
* @param check whether to check if tool exists
|
||||||
*/
|
* @returns Promise<string> path to tool
|
||||||
function which(tool, check) {
|
*/
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
function which(tool, check) {
|
||||||
if (!tool) {
|
return __awaiter(this, void 0, void 0, function* () {
|
||||||
throw new Error("parameter 'tool' is required");
|
if (!tool) {
|
||||||
}
|
throw new Error("parameter 'tool' is required");
|
||||||
// recursive when check=true
|
}
|
||||||
if (check) {
|
// recursive when check=true
|
||||||
const result = yield which(tool, false);
|
if (check) {
|
||||||
if (!result) {
|
const result = yield which(tool, false);
|
||||||
if (ioUtil.IS_WINDOWS) {
|
if (!result) {
|
||||||
throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also verify the file has a valid extension for an executable file.`);
|
if (ioUtil.IS_WINDOWS) {
|
||||||
}
|
throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also verify the file has a valid extension for an executable file.`);
|
||||||
else {
|
}
|
||||||
throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also check the file mode to verify the file is executable.`);
|
else {
|
||||||
}
|
throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also check the file mode to verify the file is executable.`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
try {
|
}
|
||||||
// build the list of extensions to try
|
try {
|
||||||
const extensions = [];
|
// build the list of extensions to try
|
||||||
if (ioUtil.IS_WINDOWS && process.env.PATHEXT) {
|
const extensions = [];
|
||||||
for (const extension of process.env.PATHEXT.split(path.delimiter)) {
|
if (ioUtil.IS_WINDOWS && process.env.PATHEXT) {
|
||||||
if (extension) {
|
for (const extension of process.env.PATHEXT.split(path.delimiter)) {
|
||||||
extensions.push(extension);
|
if (extension) {
|
||||||
}
|
extensions.push(extension);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// if it's rooted, return it if exists. otherwise return empty.
|
}
|
||||||
if (ioUtil.isRooted(tool)) {
|
// if it's rooted, return it if exists. otherwise return empty.
|
||||||
const filePath = yield ioUtil.tryGetExecutablePath(tool, extensions);
|
if (ioUtil.isRooted(tool)) {
|
||||||
if (filePath) {
|
const filePath = yield ioUtil.tryGetExecutablePath(tool, extensions);
|
||||||
return filePath;
|
if (filePath) {
|
||||||
}
|
return filePath;
|
||||||
return '';
|
}
|
||||||
}
|
return '';
|
||||||
// if any path separators, return empty
|
}
|
||||||
if (tool.includes('/') || (ioUtil.IS_WINDOWS && tool.includes('\\'))) {
|
// if any path separators, return empty
|
||||||
return '';
|
if (tool.includes('/') || (ioUtil.IS_WINDOWS && tool.includes('\\'))) {
|
||||||
}
|
return '';
|
||||||
// build the list of directories
|
}
|
||||||
//
|
// build the list of directories
|
||||||
// Note, technically "where" checks the current directory on Windows. From a task lib perspective,
|
//
|
||||||
// it feels like we should not do this. Checking the current directory seems like more of a use
|
// Note, technically "where" checks the current directory on Windows. From a toolkit perspective,
|
||||||
// case of a shell, and the which() function exposed by the task lib should strive for consistency
|
// it feels like we should not do this. Checking the current directory seems like more of a use
|
||||||
// across platforms.
|
// case of a shell, and the which() function exposed by the toolkit should strive for consistency
|
||||||
const directories = [];
|
// across platforms.
|
||||||
if (process.env.PATH) {
|
const directories = [];
|
||||||
for (const p of process.env.PATH.split(path.delimiter)) {
|
if (process.env.PATH) {
|
||||||
if (p) {
|
for (const p of process.env.PATH.split(path.delimiter)) {
|
||||||
directories.push(p);
|
if (p) {
|
||||||
}
|
directories.push(p);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// return the first match
|
}
|
||||||
for (const directory of directories) {
|
// return the first match
|
||||||
const filePath = yield ioUtil.tryGetExecutablePath(directory + path.sep + tool, extensions);
|
for (const directory of directories) {
|
||||||
if (filePath) {
|
const filePath = yield ioUtil.tryGetExecutablePath(directory + path.sep + tool, extensions);
|
||||||
return filePath;
|
if (filePath) {
|
||||||
}
|
return filePath;
|
||||||
}
|
}
|
||||||
return '';
|
}
|
||||||
}
|
return '';
|
||||||
catch (err) {
|
}
|
||||||
throw new Error(`which failed with message ${err.message}`);
|
catch (err) {
|
||||||
}
|
throw new Error(`which failed with message ${err.message}`);
|
||||||
});
|
}
|
||||||
}
|
});
|
||||||
exports.which = which;
|
}
|
||||||
function readCopyOptions(options) {
|
exports.which = which;
|
||||||
const force = options.force == null ? true : options.force;
|
function readCopyOptions(options) {
|
||||||
const recursive = Boolean(options.recursive);
|
const force = options.force == null ? true : options.force;
|
||||||
return { force, recursive };
|
const recursive = Boolean(options.recursive);
|
||||||
}
|
return { force, recursive };
|
||||||
function cpDirRecursive(sourceDir, destDir, currentDepth, force) {
|
}
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
function cpDirRecursive(sourceDir, destDir, currentDepth, force) {
|
||||||
// Ensure there is not a run away recursive copy
|
return __awaiter(this, void 0, void 0, function* () {
|
||||||
if (currentDepth >= 255)
|
// Ensure there is not a run away recursive copy
|
||||||
return;
|
if (currentDepth >= 255)
|
||||||
currentDepth++;
|
return;
|
||||||
yield mkdirP(destDir);
|
currentDepth++;
|
||||||
const files = yield ioUtil.readdir(sourceDir);
|
yield mkdirP(destDir);
|
||||||
for (const fileName of files) {
|
const files = yield ioUtil.readdir(sourceDir);
|
||||||
const srcFile = `${sourceDir}/${fileName}`;
|
for (const fileName of files) {
|
||||||
const destFile = `${destDir}/${fileName}`;
|
const srcFile = `${sourceDir}/${fileName}`;
|
||||||
const srcFileStat = yield ioUtil.lstat(srcFile);
|
const destFile = `${destDir}/${fileName}`;
|
||||||
if (srcFileStat.isDirectory()) {
|
const srcFileStat = yield ioUtil.lstat(srcFile);
|
||||||
// Recurse
|
if (srcFileStat.isDirectory()) {
|
||||||
yield cpDirRecursive(srcFile, destFile, currentDepth, force);
|
// Recurse
|
||||||
}
|
yield cpDirRecursive(srcFile, destFile, currentDepth, force);
|
||||||
else {
|
}
|
||||||
yield copyFile(srcFile, destFile, force);
|
else {
|
||||||
}
|
yield copyFile(srcFile, destFile, force);
|
||||||
}
|
}
|
||||||
// Change the mode for the newly created directory
|
}
|
||||||
yield ioUtil.chmod(destDir, (yield ioUtil.stat(sourceDir)).mode);
|
// Change the mode for the newly created directory
|
||||||
});
|
yield ioUtil.chmod(destDir, (yield ioUtil.stat(sourceDir)).mode);
|
||||||
}
|
});
|
||||||
// Buffered file copy
|
}
|
||||||
function copyFile(srcFile, destFile, force) {
|
// Buffered file copy
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
function copyFile(srcFile, destFile, force) {
|
||||||
if ((yield ioUtil.lstat(srcFile)).isSymbolicLink()) {
|
return __awaiter(this, void 0, void 0, function* () {
|
||||||
// unlink/re-link it
|
if ((yield ioUtil.lstat(srcFile)).isSymbolicLink()) {
|
||||||
try {
|
// unlink/re-link it
|
||||||
yield ioUtil.lstat(destFile);
|
try {
|
||||||
yield ioUtil.unlink(destFile);
|
yield ioUtil.lstat(destFile);
|
||||||
}
|
yield ioUtil.unlink(destFile);
|
||||||
catch (e) {
|
}
|
||||||
// Try to override file permission
|
catch (e) {
|
||||||
if (e.code === 'EPERM') {
|
// Try to override file permission
|
||||||
yield ioUtil.chmod(destFile, '0666');
|
if (e.code === 'EPERM') {
|
||||||
yield ioUtil.unlink(destFile);
|
yield ioUtil.chmod(destFile, '0666');
|
||||||
}
|
yield ioUtil.unlink(destFile);
|
||||||
// other errors = it doesn't exist, no work to do
|
}
|
||||||
}
|
// other errors = it doesn't exist, no work to do
|
||||||
// Copy over symlink
|
}
|
||||||
const symlinkFull = yield ioUtil.readlink(srcFile);
|
// Copy over symlink
|
||||||
yield ioUtil.symlink(symlinkFull, destFile, ioUtil.IS_WINDOWS ? 'junction' : null);
|
const symlinkFull = yield ioUtil.readlink(srcFile);
|
||||||
}
|
yield ioUtil.symlink(symlinkFull, destFile, ioUtil.IS_WINDOWS ? 'junction' : null);
|
||||||
else if (!(yield ioUtil.exists(destFile)) || force) {
|
}
|
||||||
yield ioUtil.copyFile(srcFile, destFile);
|
else if (!(yield ioUtil.exists(destFile)) || force) {
|
||||||
}
|
yield ioUtil.copyFile(srcFile, destFile);
|
||||||
});
|
}
|
||||||
}
|
});
|
||||||
|
}
|
||||||
//# sourceMappingURL=io.js.map
|
//# sourceMappingURL=io.js.map
|
||||||
File diff suppressed because one or more lines are too long
@ -1,7 +0,0 @@
|
|||||||
Copyright 2019 GitHub
|
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
||||||
|
|
||||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
||||||
|
|
||||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
||||||
@ -1,82 +1,82 @@
|
|||||||
# `@actions/tool-cache`
|
# `@actions/tool-cache`
|
||||||
|
|
||||||
> Functions necessary for downloading and caching tools.
|
> Functions necessary for downloading and caching tools.
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
#### Download
|
#### Download
|
||||||
|
|
||||||
You can use this to download tools (or other files) from a download URL:
|
You can use this to download tools (or other files) from a download URL:
|
||||||
|
|
||||||
```
|
```js
|
||||||
const tc = require('@actions/tool-cache');
|
const tc = require('@actions/tool-cache');
|
||||||
|
|
||||||
const node12Path = await tc.downloadTool('http://nodejs.org/dist/v12.7.0/node-v12.7.0-linux-x64.tar.gz');
|
const node12Path = await tc.downloadTool('https://nodejs.org/dist/v12.7.0/node-v12.7.0-linux-x64.tar.gz');
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Extract
|
#### Extract
|
||||||
|
|
||||||
These can then be extracted in platform specific ways:
|
These can then be extracted in platform specific ways:
|
||||||
|
|
||||||
```
|
```js
|
||||||
const tc = require('@actions/tool-cache');
|
const tc = require('@actions/tool-cache');
|
||||||
|
|
||||||
if (process.platform === 'win32') {
|
if (process.platform === 'win32') {
|
||||||
tc.downloadTool('http://nodejs.org/dist/v12.7.0/node-v12.7.0-win-x64.zip');
|
const node12Path = tc.downloadTool('https://nodejs.org/dist/v12.7.0/node-v12.7.0-win-x64.zip');
|
||||||
const node12ExtractedFolder = await tc.extractZip(node12Path, 'path/to/extract/to');
|
const node12ExtractedFolder = await tc.extractZip(node12Path, 'path/to/extract/to');
|
||||||
|
|
||||||
// Or alternately
|
// Or alternately
|
||||||
tc.downloadTool('http://nodejs.org/dist/v12.7.0/node-v12.7.0-win-x64.7z');
|
const node12Path = tc.downloadTool('https://nodejs.org/dist/v12.7.0/node-v12.7.0-win-x64.7z');
|
||||||
const node12ExtractedFolder = await tc.extract7z(node12Path, 'path/to/extract/to');
|
const node12ExtractedFolder = await tc.extract7z(node12Path, 'path/to/extract/to');
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
const node12Path = await tc.downloadTool('http://nodejs.org/dist/v12.7.0/node-v12.7.0-linux-x64.tar.gz');
|
const node12Path = await tc.downloadTool('https://nodejs.org/dist/v12.7.0/node-v12.7.0-linux-x64.tar.gz');
|
||||||
const node12ExtractedFolder = await tc.extractTar(node12Path, 'path/to/extract/to');
|
const node12ExtractedFolder = await tc.extractTar(node12Path, 'path/to/extract/to');
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Cache
|
#### Cache
|
||||||
|
|
||||||
Finally, you can cache these directories in our tool-cache. This is useful if you want to switch back and forth between versions of a tool, or save a tool between runs for private runners (private runners are still in development but are on the roadmap).
|
Finally, you can cache these directories in our tool-cache. This is useful if you want to switch back and forth between versions of a tool, or save a tool between runs for private runners (private runners are still in development but are on the roadmap).
|
||||||
|
|
||||||
You'll often want to add it to the path as part of this step:
|
You'll often want to add it to the path as part of this step:
|
||||||
|
|
||||||
```
|
```js
|
||||||
const tc = require('@actions/tool-cache');
|
const tc = require('@actions/tool-cache');
|
||||||
const core = require('@actions/core');
|
const core = require('@actions/core');
|
||||||
|
|
||||||
const node12Path = await tc.downloadTool('http://nodejs.org/dist/v12.7.0/node-v12.7.0-linux-x64.tar.gz');
|
const node12Path = await tc.downloadTool('https://nodejs.org/dist/v12.7.0/node-v12.7.0-linux-x64.tar.gz');
|
||||||
const node12ExtractedFolder = await tc.extractTar(node12Path, 'path/to/extract/to');
|
const node12ExtractedFolder = await tc.extractTar(node12Path, 'path/to/extract/to');
|
||||||
|
|
||||||
const cachedPath = await tc.cacheDir(node12ExtractedFolder, 'node', '12.7.0');
|
const cachedPath = await tc.cacheDir(node12ExtractedFolder, 'node', '12.7.0');
|
||||||
core.addPath(cachedPath);
|
core.addPath(cachedPath);
|
||||||
```
|
```
|
||||||
|
|
||||||
You can also cache files for reuse.
|
You can also cache files for reuse.
|
||||||
|
|
||||||
```
|
```js
|
||||||
const tc = require('@actions/tool-cache');
|
const tc = require('@actions/tool-cache');
|
||||||
|
|
||||||
tc.cacheFile('path/to/exe', 'destFileName.exe', 'myExeName', '1.1.0');
|
tc.cacheFile('path/to/exe', 'destFileName.exe', 'myExeName', '1.1.0');
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Find
|
#### Find
|
||||||
|
|
||||||
Finally, you can find directories and files you've previously cached:
|
Finally, you can find directories and files you've previously cached:
|
||||||
|
|
||||||
```
|
```js
|
||||||
const tc = require('@actions/tool-cache');
|
const tc = require('@actions/tool-cache');
|
||||||
const core = require('@actions/core');
|
const core = require('@actions/core');
|
||||||
|
|
||||||
const nodeDirectory = tc.find('node', '12.x', 'x64');
|
const nodeDirectory = tc.find('node', '12.x', 'x64');
|
||||||
core.addPath(nodeDirectory);
|
core.addPath(nodeDirectory);
|
||||||
```
|
```
|
||||||
|
|
||||||
You can even find all cached versions of a tool:
|
You can even find all cached versions of a tool:
|
||||||
|
|
||||||
```
|
```js
|
||||||
const tc = require('@actions/tool-cache');
|
const tc = require('@actions/tool-cache');
|
||||||
|
|
||||||
const allNodeVersions = tc.findAllVersions('node');
|
const allNodeVersions = tc.findAllVersions('node');
|
||||||
console.log(`Versions of node available: ${allNodeVersions}`);
|
console.log(`Versions of node available: ${allNodeVersions}`);
|
||||||
```
|
```
|
||||||
|
|||||||
@ -1,78 +1,79 @@
|
|||||||
export declare class HTTPError extends Error {
|
export declare class HTTPError extends Error {
|
||||||
readonly httpStatusCode: number | undefined;
|
readonly httpStatusCode: number | undefined;
|
||||||
constructor(httpStatusCode: number | undefined);
|
constructor(httpStatusCode: number | undefined);
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* Download a tool from an url and stream it into a file
|
* Download a tool from an url and stream it into a file
|
||||||
*
|
*
|
||||||
* @param url url of tool to download
|
* @param url url of tool to download
|
||||||
* @returns path to downloaded tool
|
* @returns path to downloaded tool
|
||||||
*/
|
*/
|
||||||
export declare function downloadTool(url: string): Promise<string>;
|
export declare function downloadTool(url: string): Promise<string>;
|
||||||
/**
|
/**
|
||||||
* Extract a .7z file
|
* Extract a .7z file
|
||||||
*
|
*
|
||||||
* @param file path to the .7z file
|
* @param file path to the .7z file
|
||||||
* @param dest destination directory. Optional.
|
* @param dest destination directory. Optional.
|
||||||
* @param _7zPath path to 7zr.exe. Optional, for long path support. Most .7z archives do not have this
|
* @param _7zPath path to 7zr.exe. Optional, for long path support. Most .7z archives do not have this
|
||||||
* problem. If your .7z archive contains very long paths, you can pass the path to 7zr.exe which will
|
* problem. If your .7z archive contains very long paths, you can pass the path to 7zr.exe which will
|
||||||
* gracefully handle long paths. By default 7zdec.exe is used because it is a very small program and is
|
* gracefully handle long paths. By default 7zdec.exe is used because it is a very small program and is
|
||||||
* bundled with the tool lib. However it does not support long paths. 7zr.exe is the reduced command line
|
* bundled with the tool lib. However it does not support long paths. 7zr.exe is the reduced command line
|
||||||
* interface, it is smaller than the full command line interface, and it does support long paths. At the
|
* interface, it is smaller than the full command line interface, and it does support long paths. At the
|
||||||
* time of this writing, it is freely available from the LZMA SDK that is available on the 7zip website.
|
* time of this writing, it is freely available from the LZMA SDK that is available on the 7zip website.
|
||||||
* Be sure to check the current license agreement. If 7zr.exe is bundled with your action, then the path
|
* Be sure to check the current license agreement. If 7zr.exe is bundled with your action, then the path
|
||||||
* to 7zr.exe can be pass to this function.
|
* to 7zr.exe can be pass to this function.
|
||||||
* @returns path to the destination directory
|
* @returns path to the destination directory
|
||||||
*/
|
*/
|
||||||
export declare function extract7z(file: string, dest?: string, _7zPath?: string): Promise<string>;
|
export declare function extract7z(file: string, dest?: string, _7zPath?: string): Promise<string>;
|
||||||
/**
|
/**
|
||||||
* Extract a tar
|
* Extract a tar
|
||||||
*
|
*
|
||||||
* @param file path to the tar
|
* @param file path to the tar
|
||||||
* @param dest destination directory. Optional.
|
* @param dest destination directory. Optional.
|
||||||
* @returns path to the destination directory
|
* @param flags flags for the tar. Optional.
|
||||||
*/
|
* @returns path to the destination directory
|
||||||
export declare function extractTar(file: string, dest?: string): Promise<string>;
|
*/
|
||||||
/**
|
export declare function extractTar(file: string, dest?: string, flags?: string): Promise<string>;
|
||||||
* Extract a zip
|
/**
|
||||||
*
|
* Extract a zip
|
||||||
* @param file path to the zip
|
*
|
||||||
* @param dest destination directory. Optional.
|
* @param file path to the zip
|
||||||
* @returns path to the destination directory
|
* @param dest destination directory. Optional.
|
||||||
*/
|
* @returns path to the destination directory
|
||||||
export declare function extractZip(file: string, dest?: string): Promise<string>;
|
*/
|
||||||
/**
|
export declare function extractZip(file: string, dest?: string): Promise<string>;
|
||||||
* Caches a directory and installs it into the tool cacheDir
|
/**
|
||||||
*
|
* Caches a directory and installs it into the tool cacheDir
|
||||||
* @param sourceDir the directory to cache into tools
|
*
|
||||||
* @param tool tool name
|
* @param sourceDir the directory to cache into tools
|
||||||
* @param version version of the tool. semver format
|
* @param tool tool name
|
||||||
* @param arch architecture of the tool. Optional. Defaults to machine architecture
|
* @param version version of the tool. semver format
|
||||||
*/
|
* @param arch architecture of the tool. Optional. Defaults to machine architecture
|
||||||
export declare function cacheDir(sourceDir: string, tool: string, version: string, arch?: string): Promise<string>;
|
*/
|
||||||
/**
|
export declare function cacheDir(sourceDir: string, tool: string, version: string, arch?: string): Promise<string>;
|
||||||
* Caches a downloaded file (GUID) and installs it
|
/**
|
||||||
* into the tool cache with a given targetName
|
* Caches a downloaded file (GUID) and installs it
|
||||||
*
|
* into the tool cache with a given targetName
|
||||||
* @param sourceFile the file to cache into tools. Typically a result of downloadTool which is a guid.
|
*
|
||||||
* @param targetFile the name of the file name in the tools directory
|
* @param sourceFile the file to cache into tools. Typically a result of downloadTool which is a guid.
|
||||||
* @param tool tool name
|
* @param targetFile the name of the file name in the tools directory
|
||||||
* @param version version of the tool. semver format
|
* @param tool tool name
|
||||||
* @param arch architecture of the tool. Optional. Defaults to machine architecture
|
* @param version version of the tool. semver format
|
||||||
*/
|
* @param arch architecture of the tool. Optional. Defaults to machine architecture
|
||||||
export declare function cacheFile(sourceFile: string, targetFile: string, tool: string, version: string, arch?: string): Promise<string>;
|
*/
|
||||||
/**
|
export declare function cacheFile(sourceFile: string, targetFile: string, tool: string, version: string, arch?: string): Promise<string>;
|
||||||
* Finds the path to a tool version in the local installed tool cache
|
/**
|
||||||
*
|
* Finds the path to a tool version in the local installed tool cache
|
||||||
* @param toolName name of the tool
|
*
|
||||||
* @param versionSpec version of the tool
|
* @param toolName name of the tool
|
||||||
* @param arch optional arch. defaults to arch of computer
|
* @param versionSpec version of the tool
|
||||||
*/
|
* @param arch optional arch. defaults to arch of computer
|
||||||
export declare function find(toolName: string, versionSpec: string, arch?: string): string;
|
*/
|
||||||
/**
|
export declare function find(toolName: string, versionSpec: string, arch?: string): string;
|
||||||
* Finds the paths to all versions of a tool that are installed in the local tool cache
|
/**
|
||||||
*
|
* Finds the paths to all versions of a tool that are installed in the local tool cache
|
||||||
* @param toolName name of the tool
|
*
|
||||||
* @param arch optional arch. defaults to arch of computer
|
* @param toolName name of the tool
|
||||||
*/
|
* @param arch optional arch. defaults to arch of computer
|
||||||
export declare function findAllVersions(toolName: string, arch?: string): string[];
|
*/
|
||||||
|
export declare function findAllVersions(toolName: string, arch?: string): string[];
|
||||||
|
|||||||
@ -1,436 +1,438 @@
|
|||||||
"use strict";
|
"use strict";
|
||||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||||
return new (P || (P = Promise))(function (resolve, reject) {
|
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
return new (P || (P = Promise))(function (resolve, reject) {
|
||||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||||
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
|
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
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 });
|
};
|
||||||
const core = require("@actions/core");
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
const io = require("@actions/io");
|
const core = require("@actions/core");
|
||||||
const fs = require("fs");
|
const io = require("@actions/io");
|
||||||
const os = require("os");
|
const fs = require("fs");
|
||||||
const path = require("path");
|
const os = require("os");
|
||||||
const httpm = require("typed-rest-client/HttpClient");
|
const path = require("path");
|
||||||
const semver = require("semver");
|
const httpm = require("typed-rest-client/HttpClient");
|
||||||
const uuidV4 = require("uuid/v4");
|
const semver = require("semver");
|
||||||
const exec_1 = require("@actions/exec/lib/exec");
|
const uuidV4 = require("uuid/v4");
|
||||||
const assert_1 = require("assert");
|
const exec_1 = require("@actions/exec/lib/exec");
|
||||||
class HTTPError extends Error {
|
const assert_1 = require("assert");
|
||||||
constructor(httpStatusCode) {
|
class HTTPError extends Error {
|
||||||
super(`Unexpected HTTP response: ${httpStatusCode}`);
|
constructor(httpStatusCode) {
|
||||||
this.httpStatusCode = httpStatusCode;
|
super(`Unexpected HTTP response: ${httpStatusCode}`);
|
||||||
Object.setPrototypeOf(this, new.target.prototype);
|
this.httpStatusCode = httpStatusCode;
|
||||||
}
|
Object.setPrototypeOf(this, new.target.prototype);
|
||||||
}
|
}
|
||||||
exports.HTTPError = HTTPError;
|
}
|
||||||
const IS_WINDOWS = process.platform === 'win32';
|
exports.HTTPError = HTTPError;
|
||||||
const userAgent = 'actions/tool-cache';
|
const IS_WINDOWS = process.platform === 'win32';
|
||||||
// On load grab temp directory and cache directory and remove them from env (currently don't want to expose this)
|
const userAgent = 'actions/tool-cache';
|
||||||
let tempDirectory = process.env['RUNNER_TEMP'] || '';
|
// On load grab temp directory and cache directory and remove them from env (currently don't want to expose this)
|
||||||
let cacheRoot = process.env['RUNNER_TOOL_CACHE'] || '';
|
let tempDirectory = process.env['RUNNER_TEMP'] || '';
|
||||||
// If directories not found, place them in common temp locations
|
let cacheRoot = process.env['RUNNER_TOOL_CACHE'] || '';
|
||||||
if (!tempDirectory || !cacheRoot) {
|
// If directories not found, place them in common temp locations
|
||||||
let baseLocation;
|
if (!tempDirectory || !cacheRoot) {
|
||||||
if (IS_WINDOWS) {
|
let baseLocation;
|
||||||
// On windows use the USERPROFILE env variable
|
if (IS_WINDOWS) {
|
||||||
baseLocation = process.env['USERPROFILE'] || 'C:\\';
|
// On windows use the USERPROFILE env variable
|
||||||
}
|
baseLocation = process.env['USERPROFILE'] || 'C:\\';
|
||||||
else {
|
}
|
||||||
if (process.platform === 'darwin') {
|
else {
|
||||||
baseLocation = '/Users';
|
if (process.platform === 'darwin') {
|
||||||
}
|
baseLocation = '/Users';
|
||||||
else {
|
}
|
||||||
baseLocation = '/home';
|
else {
|
||||||
}
|
baseLocation = '/home';
|
||||||
}
|
}
|
||||||
if (!tempDirectory) {
|
}
|
||||||
tempDirectory = path.join(baseLocation, 'actions', 'temp');
|
if (!tempDirectory) {
|
||||||
}
|
tempDirectory = path.join(baseLocation, 'actions', 'temp');
|
||||||
if (!cacheRoot) {
|
}
|
||||||
cacheRoot = path.join(baseLocation, 'actions', 'cache');
|
if (!cacheRoot) {
|
||||||
}
|
cacheRoot = path.join(baseLocation, 'actions', 'cache');
|
||||||
}
|
}
|
||||||
/**
|
}
|
||||||
* Download a tool from an url and stream it into a file
|
/**
|
||||||
*
|
* Download a tool from an url and stream it into a file
|
||||||
* @param url url of tool to download
|
*
|
||||||
* @returns path to downloaded tool
|
* @param url url of tool to download
|
||||||
*/
|
* @returns path to downloaded tool
|
||||||
function downloadTool(url) {
|
*/
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
function downloadTool(url) {
|
||||||
// Wrap in a promise so that we can resolve from within stream callbacks
|
return __awaiter(this, void 0, void 0, function* () {
|
||||||
return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
|
// Wrap in a promise so that we can resolve from within stream callbacks
|
||||||
try {
|
return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
|
||||||
const http = new httpm.HttpClient(userAgent, [], {
|
try {
|
||||||
allowRetries: true,
|
const http = new httpm.HttpClient(userAgent, [], {
|
||||||
maxRetries: 3
|
allowRetries: true,
|
||||||
});
|
maxRetries: 3
|
||||||
const destPath = path.join(tempDirectory, uuidV4());
|
});
|
||||||
yield io.mkdirP(tempDirectory);
|
const destPath = path.join(tempDirectory, uuidV4());
|
||||||
core.debug(`Downloading ${url}`);
|
yield io.mkdirP(tempDirectory);
|
||||||
core.debug(`Downloading ${destPath}`);
|
core.debug(`Downloading ${url}`);
|
||||||
if (fs.existsSync(destPath)) {
|
core.debug(`Downloading ${destPath}`);
|
||||||
throw new Error(`Destination file path ${destPath} already exists`);
|
if (fs.existsSync(destPath)) {
|
||||||
}
|
throw new Error(`Destination file path ${destPath} already exists`);
|
||||||
const response = yield http.get(url);
|
}
|
||||||
if (response.message.statusCode !== 200) {
|
const response = yield http.get(url);
|
||||||
const err = new HTTPError(response.message.statusCode);
|
if (response.message.statusCode !== 200) {
|
||||||
core.debug(`Failed to download from "${url}". Code(${response.message.statusCode}) Message(${response.message.statusMessage})`);
|
const err = new HTTPError(response.message.statusCode);
|
||||||
throw err;
|
core.debug(`Failed to download from "${url}". Code(${response.message.statusCode}) Message(${response.message.statusMessage})`);
|
||||||
}
|
throw err;
|
||||||
const file = fs.createWriteStream(destPath);
|
}
|
||||||
file.on('open', () => __awaiter(this, void 0, void 0, function* () {
|
const file = fs.createWriteStream(destPath);
|
||||||
try {
|
file.on('open', () => __awaiter(this, void 0, void 0, function* () {
|
||||||
const stream = response.message.pipe(file);
|
try {
|
||||||
stream.on('close', () => {
|
const stream = response.message.pipe(file);
|
||||||
core.debug('download complete');
|
stream.on('close', () => {
|
||||||
resolve(destPath);
|
core.debug('download complete');
|
||||||
});
|
resolve(destPath);
|
||||||
}
|
});
|
||||||
catch (err) {
|
}
|
||||||
core.debug(`Failed to download from "${url}". Code(${response.message.statusCode}) Message(${response.message.statusMessage})`);
|
catch (err) {
|
||||||
reject(err);
|
core.debug(`Failed to download from "${url}". Code(${response.message.statusCode}) Message(${response.message.statusMessage})`);
|
||||||
}
|
reject(err);
|
||||||
}));
|
}
|
||||||
file.on('error', err => {
|
}));
|
||||||
file.end();
|
file.on('error', err => {
|
||||||
reject(err);
|
file.end();
|
||||||
});
|
reject(err);
|
||||||
}
|
});
|
||||||
catch (err) {
|
}
|
||||||
reject(err);
|
catch (err) {
|
||||||
}
|
reject(err);
|
||||||
}));
|
}
|
||||||
});
|
}));
|
||||||
}
|
});
|
||||||
exports.downloadTool = downloadTool;
|
}
|
||||||
/**
|
exports.downloadTool = downloadTool;
|
||||||
* Extract a .7z file
|
/**
|
||||||
*
|
* Extract a .7z file
|
||||||
* @param file path to the .7z file
|
*
|
||||||
* @param dest destination directory. Optional.
|
* @param file path to the .7z file
|
||||||
* @param _7zPath path to 7zr.exe. Optional, for long path support. Most .7z archives do not have this
|
* @param dest destination directory. Optional.
|
||||||
* problem. If your .7z archive contains very long paths, you can pass the path to 7zr.exe which will
|
* @param _7zPath path to 7zr.exe. Optional, for long path support. Most .7z archives do not have this
|
||||||
* gracefully handle long paths. By default 7zdec.exe is used because it is a very small program and is
|
* problem. If your .7z archive contains very long paths, you can pass the path to 7zr.exe which will
|
||||||
* bundled with the tool lib. However it does not support long paths. 7zr.exe is the reduced command line
|
* gracefully handle long paths. By default 7zdec.exe is used because it is a very small program and is
|
||||||
* interface, it is smaller than the full command line interface, and it does support long paths. At the
|
* bundled with the tool lib. However it does not support long paths. 7zr.exe is the reduced command line
|
||||||
* time of this writing, it is freely available from the LZMA SDK that is available on the 7zip website.
|
* interface, it is smaller than the full command line interface, and it does support long paths. At the
|
||||||
* Be sure to check the current license agreement. If 7zr.exe is bundled with your action, then the path
|
* time of this writing, it is freely available from the LZMA SDK that is available on the 7zip website.
|
||||||
* to 7zr.exe can be pass to this function.
|
* Be sure to check the current license agreement. If 7zr.exe is bundled with your action, then the path
|
||||||
* @returns path to the destination directory
|
* to 7zr.exe can be pass to this function.
|
||||||
*/
|
* @returns path to the destination directory
|
||||||
function extract7z(file, dest, _7zPath) {
|
*/
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
function extract7z(file, dest, _7zPath) {
|
||||||
assert_1.ok(IS_WINDOWS, 'extract7z() not supported on current OS');
|
return __awaiter(this, void 0, void 0, function* () {
|
||||||
assert_1.ok(file, 'parameter "file" is required');
|
assert_1.ok(IS_WINDOWS, 'extract7z() not supported on current OS');
|
||||||
dest = dest || (yield _createExtractFolder(dest));
|
assert_1.ok(file, 'parameter "file" is required');
|
||||||
const originalCwd = process.cwd();
|
dest = dest || (yield _createExtractFolder(dest));
|
||||||
process.chdir(dest);
|
const originalCwd = process.cwd();
|
||||||
if (_7zPath) {
|
process.chdir(dest);
|
||||||
try {
|
if (_7zPath) {
|
||||||
const args = [
|
try {
|
||||||
'x',
|
const args = [
|
||||||
'-bb1',
|
'x',
|
||||||
'-bd',
|
'-bb1',
|
||||||
'-sccUTF-8',
|
'-bd',
|
||||||
file
|
'-sccUTF-8',
|
||||||
];
|
file
|
||||||
const options = {
|
];
|
||||||
silent: true
|
const options = {
|
||||||
};
|
silent: true
|
||||||
yield exec_1.exec(`"${_7zPath}"`, args, options);
|
};
|
||||||
}
|
yield exec_1.exec(`"${_7zPath}"`, args, options);
|
||||||
finally {
|
}
|
||||||
process.chdir(originalCwd);
|
finally {
|
||||||
}
|
process.chdir(originalCwd);
|
||||||
}
|
}
|
||||||
else {
|
}
|
||||||
const escapedScript = path
|
else {
|
||||||
.join(__dirname, '..', 'scripts', 'Invoke-7zdec.ps1')
|
const escapedScript = path
|
||||||
.replace(/'/g, "''")
|
.join(__dirname, '..', 'scripts', 'Invoke-7zdec.ps1')
|
||||||
.replace(/"|\n|\r/g, ''); // double-up single quotes, remove double quotes and newlines
|
.replace(/'/g, "''")
|
||||||
const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, '');
|
.replace(/"|\n|\r/g, ''); // double-up single quotes, remove double quotes and newlines
|
||||||
const escapedTarget = dest.replace(/'/g, "''").replace(/"|\n|\r/g, '');
|
const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, '');
|
||||||
const command = `& '${escapedScript}' -Source '${escapedFile}' -Target '${escapedTarget}'`;
|
const escapedTarget = dest.replace(/'/g, "''").replace(/"|\n|\r/g, '');
|
||||||
const args = [
|
const command = `& '${escapedScript}' -Source '${escapedFile}' -Target '${escapedTarget}'`;
|
||||||
'-NoLogo',
|
const args = [
|
||||||
'-Sta',
|
'-NoLogo',
|
||||||
'-NoProfile',
|
'-Sta',
|
||||||
'-NonInteractive',
|
'-NoProfile',
|
||||||
'-ExecutionPolicy',
|
'-NonInteractive',
|
||||||
'Unrestricted',
|
'-ExecutionPolicy',
|
||||||
'-Command',
|
'Unrestricted',
|
||||||
command
|
'-Command',
|
||||||
];
|
command
|
||||||
const options = {
|
];
|
||||||
silent: true
|
const options = {
|
||||||
};
|
silent: true
|
||||||
try {
|
};
|
||||||
const powershellPath = yield io.which('powershell', true);
|
try {
|
||||||
yield exec_1.exec(`"${powershellPath}"`, args, options);
|
const powershellPath = yield io.which('powershell', true);
|
||||||
}
|
yield exec_1.exec(`"${powershellPath}"`, args, options);
|
||||||
finally {
|
}
|
||||||
process.chdir(originalCwd);
|
finally {
|
||||||
}
|
process.chdir(originalCwd);
|
||||||
}
|
}
|
||||||
return dest;
|
}
|
||||||
});
|
return dest;
|
||||||
}
|
});
|
||||||
exports.extract7z = extract7z;
|
}
|
||||||
/**
|
exports.extract7z = extract7z;
|
||||||
* Extract a tar
|
/**
|
||||||
*
|
* Extract a tar
|
||||||
* @param file path to the tar
|
*
|
||||||
* @param dest destination directory. Optional.
|
* @param file path to the tar
|
||||||
* @returns path to the destination directory
|
* @param dest destination directory. Optional.
|
||||||
*/
|
* @param flags flags for the tar. Optional.
|
||||||
function extractTar(file, dest) {
|
* @returns path to the destination directory
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
*/
|
||||||
if (!file) {
|
function extractTar(file, dest, flags = 'xz') {
|
||||||
throw new Error("parameter 'file' is required");
|
return __awaiter(this, void 0, void 0, function* () {
|
||||||
}
|
if (!file) {
|
||||||
dest = dest || (yield _createExtractFolder(dest));
|
throw new Error("parameter 'file' is required");
|
||||||
const tarPath = yield io.which('tar', true);
|
}
|
||||||
yield exec_1.exec(`"${tarPath}"`, ['xzC', dest, '-f', file]);
|
dest = dest || (yield _createExtractFolder(dest));
|
||||||
return dest;
|
const tarPath = yield io.which('tar', true);
|
||||||
});
|
yield exec_1.exec(`"${tarPath}"`, [flags, '-C', dest, '-f', file]);
|
||||||
}
|
return dest;
|
||||||
exports.extractTar = extractTar;
|
});
|
||||||
/**
|
}
|
||||||
* Extract a zip
|
exports.extractTar = extractTar;
|
||||||
*
|
/**
|
||||||
* @param file path to the zip
|
* Extract a zip
|
||||||
* @param dest destination directory. Optional.
|
*
|
||||||
* @returns path to the destination directory
|
* @param file path to the zip
|
||||||
*/
|
* @param dest destination directory. Optional.
|
||||||
function extractZip(file, dest) {
|
* @returns path to the destination directory
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
*/
|
||||||
if (!file) {
|
function extractZip(file, dest) {
|
||||||
throw new Error("parameter 'file' is required");
|
return __awaiter(this, void 0, void 0, function* () {
|
||||||
}
|
if (!file) {
|
||||||
dest = dest || (yield _createExtractFolder(dest));
|
throw new Error("parameter 'file' is required");
|
||||||
if (IS_WINDOWS) {
|
}
|
||||||
yield extractZipWin(file, dest);
|
dest = dest || (yield _createExtractFolder(dest));
|
||||||
}
|
if (IS_WINDOWS) {
|
||||||
else {
|
yield extractZipWin(file, dest);
|
||||||
yield extractZipNix(file, dest);
|
}
|
||||||
}
|
else {
|
||||||
return dest;
|
yield extractZipNix(file, dest);
|
||||||
});
|
}
|
||||||
}
|
return dest;
|
||||||
exports.extractZip = extractZip;
|
});
|
||||||
function extractZipWin(file, dest) {
|
}
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
exports.extractZip = extractZip;
|
||||||
// build the powershell command
|
function extractZipWin(file, dest) {
|
||||||
const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ''); // double-up single quotes, remove double quotes and newlines
|
return __awaiter(this, void 0, void 0, function* () {
|
||||||
const escapedDest = dest.replace(/'/g, "''").replace(/"|\n|\r/g, '');
|
// build the powershell command
|
||||||
const command = `$ErrorActionPreference = 'Stop' ; try { Add-Type -AssemblyName System.IO.Compression.FileSystem } catch { } ; [System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}')`;
|
const escapedFile = file.replace(/'/g, "''").replace(/"|\n|\r/g, ''); // double-up single quotes, remove double quotes and newlines
|
||||||
// run powershell
|
const escapedDest = dest.replace(/'/g, "''").replace(/"|\n|\r/g, '');
|
||||||
const powershellPath = yield io.which('powershell');
|
const command = `$ErrorActionPreference = 'Stop' ; try { Add-Type -AssemblyName System.IO.Compression.FileSystem } catch { } ; [System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFile}', '${escapedDest}')`;
|
||||||
const args = [
|
// run powershell
|
||||||
'-NoLogo',
|
const powershellPath = yield io.which('powershell');
|
||||||
'-Sta',
|
const args = [
|
||||||
'-NoProfile',
|
'-NoLogo',
|
||||||
'-NonInteractive',
|
'-Sta',
|
||||||
'-ExecutionPolicy',
|
'-NoProfile',
|
||||||
'Unrestricted',
|
'-NonInteractive',
|
||||||
'-Command',
|
'-ExecutionPolicy',
|
||||||
command
|
'Unrestricted',
|
||||||
];
|
'-Command',
|
||||||
yield exec_1.exec(`"${powershellPath}"`, args);
|
command
|
||||||
});
|
];
|
||||||
}
|
yield exec_1.exec(`"${powershellPath}"`, args);
|
||||||
function extractZipNix(file, dest) {
|
});
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
}
|
||||||
const unzipPath = path.join(__dirname, '..', 'scripts', 'externals', 'unzip');
|
function extractZipNix(file, dest) {
|
||||||
yield exec_1.exec(`"${unzipPath}"`, [file], { cwd: dest });
|
return __awaiter(this, void 0, void 0, function* () {
|
||||||
});
|
const unzipPath = yield io.which('unzip');
|
||||||
}
|
yield exec_1.exec(`"${unzipPath}"`, [file], { cwd: dest });
|
||||||
/**
|
});
|
||||||
* Caches a directory and installs it into the tool cacheDir
|
}
|
||||||
*
|
/**
|
||||||
* @param sourceDir the directory to cache into tools
|
* Caches a directory and installs it into the tool cacheDir
|
||||||
* @param tool tool name
|
*
|
||||||
* @param version version of the tool. semver format
|
* @param sourceDir the directory to cache into tools
|
||||||
* @param arch architecture of the tool. Optional. Defaults to machine architecture
|
* @param tool tool name
|
||||||
*/
|
* @param version version of the tool. semver format
|
||||||
function cacheDir(sourceDir, tool, version, arch) {
|
* @param arch architecture of the tool. Optional. Defaults to machine architecture
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
*/
|
||||||
version = semver.clean(version) || version;
|
function cacheDir(sourceDir, tool, version, arch) {
|
||||||
arch = arch || os.arch();
|
return __awaiter(this, void 0, void 0, function* () {
|
||||||
core.debug(`Caching tool ${tool} ${version} ${arch}`);
|
version = semver.clean(version) || version;
|
||||||
core.debug(`source dir: ${sourceDir}`);
|
arch = arch || os.arch();
|
||||||
if (!fs.statSync(sourceDir).isDirectory()) {
|
core.debug(`Caching tool ${tool} ${version} ${arch}`);
|
||||||
throw new Error('sourceDir is not a directory');
|
core.debug(`source dir: ${sourceDir}`);
|
||||||
}
|
if (!fs.statSync(sourceDir).isDirectory()) {
|
||||||
// Create the tool dir
|
throw new Error('sourceDir is not a directory');
|
||||||
const destPath = yield _createToolPath(tool, version, arch);
|
}
|
||||||
// copy each child item. do not move. move can fail on Windows
|
// Create the tool dir
|
||||||
// due to anti-virus software having an open handle on a file.
|
const destPath = yield _createToolPath(tool, version, arch);
|
||||||
for (const itemName of fs.readdirSync(sourceDir)) {
|
// copy each child item. do not move. move can fail on Windows
|
||||||
const s = path.join(sourceDir, itemName);
|
// due to anti-virus software having an open handle on a file.
|
||||||
yield io.cp(s, destPath, { recursive: true });
|
for (const itemName of fs.readdirSync(sourceDir)) {
|
||||||
}
|
const s = path.join(sourceDir, itemName);
|
||||||
// write .complete
|
yield io.cp(s, destPath, { recursive: true });
|
||||||
_completeToolPath(tool, version, arch);
|
}
|
||||||
return destPath;
|
// write .complete
|
||||||
});
|
_completeToolPath(tool, version, arch);
|
||||||
}
|
return destPath;
|
||||||
exports.cacheDir = cacheDir;
|
});
|
||||||
/**
|
}
|
||||||
* Caches a downloaded file (GUID) and installs it
|
exports.cacheDir = cacheDir;
|
||||||
* into the tool cache with a given targetName
|
/**
|
||||||
*
|
* Caches a downloaded file (GUID) and installs it
|
||||||
* @param sourceFile the file to cache into tools. Typically a result of downloadTool which is a guid.
|
* into the tool cache with a given targetName
|
||||||
* @param targetFile the name of the file name in the tools directory
|
*
|
||||||
* @param tool tool name
|
* @param sourceFile the file to cache into tools. Typically a result of downloadTool which is a guid.
|
||||||
* @param version version of the tool. semver format
|
* @param targetFile the name of the file name in the tools directory
|
||||||
* @param arch architecture of the tool. Optional. Defaults to machine architecture
|
* @param tool tool name
|
||||||
*/
|
* @param version version of the tool. semver format
|
||||||
function cacheFile(sourceFile, targetFile, tool, version, arch) {
|
* @param arch architecture of the tool. Optional. Defaults to machine architecture
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
*/
|
||||||
version = semver.clean(version) || version;
|
function cacheFile(sourceFile, targetFile, tool, version, arch) {
|
||||||
arch = arch || os.arch();
|
return __awaiter(this, void 0, void 0, function* () {
|
||||||
core.debug(`Caching tool ${tool} ${version} ${arch}`);
|
version = semver.clean(version) || version;
|
||||||
core.debug(`source file: ${sourceFile}`);
|
arch = arch || os.arch();
|
||||||
if (!fs.statSync(sourceFile).isFile()) {
|
core.debug(`Caching tool ${tool} ${version} ${arch}`);
|
||||||
throw new Error('sourceFile is not a file');
|
core.debug(`source file: ${sourceFile}`);
|
||||||
}
|
if (!fs.statSync(sourceFile).isFile()) {
|
||||||
// create the tool dir
|
throw new Error('sourceFile is not a file');
|
||||||
const destFolder = yield _createToolPath(tool, version, arch);
|
}
|
||||||
// copy instead of move. move can fail on Windows due to
|
// create the tool dir
|
||||||
// anti-virus software having an open handle on a file.
|
const destFolder = yield _createToolPath(tool, version, arch);
|
||||||
const destPath = path.join(destFolder, targetFile);
|
// copy instead of move. move can fail on Windows due to
|
||||||
core.debug(`destination file ${destPath}`);
|
// anti-virus software having an open handle on a file.
|
||||||
yield io.cp(sourceFile, destPath);
|
const destPath = path.join(destFolder, targetFile);
|
||||||
// write .complete
|
core.debug(`destination file ${destPath}`);
|
||||||
_completeToolPath(tool, version, arch);
|
yield io.cp(sourceFile, destPath);
|
||||||
return destFolder;
|
// write .complete
|
||||||
});
|
_completeToolPath(tool, version, arch);
|
||||||
}
|
return destFolder;
|
||||||
exports.cacheFile = cacheFile;
|
});
|
||||||
/**
|
}
|
||||||
* Finds the path to a tool version in the local installed tool cache
|
exports.cacheFile = cacheFile;
|
||||||
*
|
/**
|
||||||
* @param toolName name of the tool
|
* Finds the path to a tool version in the local installed tool cache
|
||||||
* @param versionSpec version of the tool
|
*
|
||||||
* @param arch optional arch. defaults to arch of computer
|
* @param toolName name of the tool
|
||||||
*/
|
* @param versionSpec version of the tool
|
||||||
function find(toolName, versionSpec, arch) {
|
* @param arch optional arch. defaults to arch of computer
|
||||||
if (!toolName) {
|
*/
|
||||||
throw new Error('toolName parameter is required');
|
function find(toolName, versionSpec, arch) {
|
||||||
}
|
if (!toolName) {
|
||||||
if (!versionSpec) {
|
throw new Error('toolName parameter is required');
|
||||||
throw new Error('versionSpec parameter is required');
|
}
|
||||||
}
|
if (!versionSpec) {
|
||||||
arch = arch || os.arch();
|
throw new Error('versionSpec parameter is required');
|
||||||
// attempt to resolve an explicit version
|
}
|
||||||
if (!_isExplicitVersion(versionSpec)) {
|
arch = arch || os.arch();
|
||||||
const localVersions = findAllVersions(toolName, arch);
|
// attempt to resolve an explicit version
|
||||||
const match = _evaluateVersions(localVersions, versionSpec);
|
if (!_isExplicitVersion(versionSpec)) {
|
||||||
versionSpec = match;
|
const localVersions = findAllVersions(toolName, arch);
|
||||||
}
|
const match = _evaluateVersions(localVersions, versionSpec);
|
||||||
// check for the explicit version in the cache
|
versionSpec = match;
|
||||||
let toolPath = '';
|
}
|
||||||
if (versionSpec) {
|
// check for the explicit version in the cache
|
||||||
versionSpec = semver.clean(versionSpec) || '';
|
let toolPath = '';
|
||||||
const cachePath = path.join(cacheRoot, toolName, versionSpec, arch);
|
if (versionSpec) {
|
||||||
core.debug(`checking cache: ${cachePath}`);
|
versionSpec = semver.clean(versionSpec) || '';
|
||||||
if (fs.existsSync(cachePath) && fs.existsSync(`${cachePath}.complete`)) {
|
const cachePath = path.join(cacheRoot, toolName, versionSpec, arch);
|
||||||
core.debug(`Found tool in cache ${toolName} ${versionSpec} ${arch}`);
|
core.debug(`checking cache: ${cachePath}`);
|
||||||
toolPath = cachePath;
|
if (fs.existsSync(cachePath) && fs.existsSync(`${cachePath}.complete`)) {
|
||||||
}
|
core.debug(`Found tool in cache ${toolName} ${versionSpec} ${arch}`);
|
||||||
else {
|
toolPath = cachePath;
|
||||||
core.debug('not found');
|
}
|
||||||
}
|
else {
|
||||||
}
|
core.debug('not found');
|
||||||
return toolPath;
|
}
|
||||||
}
|
}
|
||||||
exports.find = find;
|
return toolPath;
|
||||||
/**
|
}
|
||||||
* Finds the paths to all versions of a tool that are installed in the local tool cache
|
exports.find = find;
|
||||||
*
|
/**
|
||||||
* @param toolName name of the tool
|
* Finds the paths to all versions of a tool that are installed in the local tool cache
|
||||||
* @param arch optional arch. defaults to arch of computer
|
*
|
||||||
*/
|
* @param toolName name of the tool
|
||||||
function findAllVersions(toolName, arch) {
|
* @param arch optional arch. defaults to arch of computer
|
||||||
const versions = [];
|
*/
|
||||||
arch = arch || os.arch();
|
function findAllVersions(toolName, arch) {
|
||||||
const toolPath = path.join(cacheRoot, toolName);
|
const versions = [];
|
||||||
if (fs.existsSync(toolPath)) {
|
arch = arch || os.arch();
|
||||||
const children = fs.readdirSync(toolPath);
|
const toolPath = path.join(cacheRoot, toolName);
|
||||||
for (const child of children) {
|
if (fs.existsSync(toolPath)) {
|
||||||
if (_isExplicitVersion(child)) {
|
const children = fs.readdirSync(toolPath);
|
||||||
const fullPath = path.join(toolPath, child, arch || '');
|
for (const child of children) {
|
||||||
if (fs.existsSync(fullPath) && fs.existsSync(`${fullPath}.complete`)) {
|
if (_isExplicitVersion(child)) {
|
||||||
versions.push(child);
|
const fullPath = path.join(toolPath, child, arch || '');
|
||||||
}
|
if (fs.existsSync(fullPath) && fs.existsSync(`${fullPath}.complete`)) {
|
||||||
}
|
versions.push(child);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return versions;
|
}
|
||||||
}
|
}
|
||||||
exports.findAllVersions = findAllVersions;
|
return versions;
|
||||||
function _createExtractFolder(dest) {
|
}
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
exports.findAllVersions = findAllVersions;
|
||||||
if (!dest) {
|
function _createExtractFolder(dest) {
|
||||||
// create a temp dir
|
return __awaiter(this, void 0, void 0, function* () {
|
||||||
dest = path.join(tempDirectory, uuidV4());
|
if (!dest) {
|
||||||
}
|
// create a temp dir
|
||||||
yield io.mkdirP(dest);
|
dest = path.join(tempDirectory, uuidV4());
|
||||||
return dest;
|
}
|
||||||
});
|
yield io.mkdirP(dest);
|
||||||
}
|
return dest;
|
||||||
function _createToolPath(tool, version, arch) {
|
});
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
}
|
||||||
const folderPath = path.join(cacheRoot, tool, semver.clean(version) || version, arch || '');
|
function _createToolPath(tool, version, arch) {
|
||||||
core.debug(`destination ${folderPath}`);
|
return __awaiter(this, void 0, void 0, function* () {
|
||||||
const markerPath = `${folderPath}.complete`;
|
const folderPath = path.join(cacheRoot, tool, semver.clean(version) || version, arch || '');
|
||||||
yield io.rmRF(folderPath);
|
core.debug(`destination ${folderPath}`);
|
||||||
yield io.rmRF(markerPath);
|
const markerPath = `${folderPath}.complete`;
|
||||||
yield io.mkdirP(folderPath);
|
yield io.rmRF(folderPath);
|
||||||
return folderPath;
|
yield io.rmRF(markerPath);
|
||||||
});
|
yield io.mkdirP(folderPath);
|
||||||
}
|
return folderPath;
|
||||||
function _completeToolPath(tool, version, arch) {
|
});
|
||||||
const folderPath = path.join(cacheRoot, tool, semver.clean(version) || version, arch || '');
|
}
|
||||||
const markerPath = `${folderPath}.complete`;
|
function _completeToolPath(tool, version, arch) {
|
||||||
fs.writeFileSync(markerPath, '');
|
const folderPath = path.join(cacheRoot, tool, semver.clean(version) || version, arch || '');
|
||||||
core.debug('finished caching tool');
|
const markerPath = `${folderPath}.complete`;
|
||||||
}
|
fs.writeFileSync(markerPath, '');
|
||||||
function _isExplicitVersion(versionSpec) {
|
core.debug('finished caching tool');
|
||||||
const c = semver.clean(versionSpec) || '';
|
}
|
||||||
core.debug(`isExplicit: ${c}`);
|
function _isExplicitVersion(versionSpec) {
|
||||||
const valid = semver.valid(c) != null;
|
const c = semver.clean(versionSpec) || '';
|
||||||
core.debug(`explicit? ${valid}`);
|
core.debug(`isExplicit: ${c}`);
|
||||||
return valid;
|
const valid = semver.valid(c) != null;
|
||||||
}
|
core.debug(`explicit? ${valid}`);
|
||||||
function _evaluateVersions(versions, versionSpec) {
|
return valid;
|
||||||
let version = '';
|
}
|
||||||
core.debug(`evaluating ${versions.length} versions`);
|
function _evaluateVersions(versions, versionSpec) {
|
||||||
versions = versions.sort((a, b) => {
|
let version = '';
|
||||||
if (semver.gt(a, b)) {
|
core.debug(`evaluating ${versions.length} versions`);
|
||||||
return 1;
|
versions = versions.sort((a, b) => {
|
||||||
}
|
if (semver.gt(a, b)) {
|
||||||
return -1;
|
return 1;
|
||||||
});
|
}
|
||||||
for (let i = versions.length - 1; i >= 0; i--) {
|
return -1;
|
||||||
const potential = versions[i];
|
});
|
||||||
const satisfied = semver.satisfies(potential, versionSpec);
|
for (let i = versions.length - 1; i >= 0; i--) {
|
||||||
if (satisfied) {
|
const potential = versions[i];
|
||||||
version = potential;
|
const satisfied = semver.satisfies(potential, versionSpec);
|
||||||
break;
|
if (satisfied) {
|
||||||
}
|
version = potential;
|
||||||
}
|
break;
|
||||||
if (version) {
|
}
|
||||||
core.debug(`matched: ${version}`);
|
}
|
||||||
}
|
if (version) {
|
||||||
else {
|
core.debug(`matched: ${version}`);
|
||||||
core.debug('match not found');
|
}
|
||||||
}
|
else {
|
||||||
return version;
|
core.debug('match not found');
|
||||||
}
|
}
|
||||||
|
return version;
|
||||||
|
}
|
||||||
//# sourceMappingURL=tool-cache.js.map
|
//# sourceMappingURL=tool-cache.js.map
|
||||||
File diff suppressed because one or more lines are too long
@ -1,60 +1,60 @@
|
|||||||
[CmdletBinding()]
|
[CmdletBinding()]
|
||||||
param(
|
param(
|
||||||
[Parameter(Mandatory = $true)]
|
[Parameter(Mandatory = $true)]
|
||||||
[string]$Source,
|
[string]$Source,
|
||||||
|
|
||||||
[Parameter(Mandatory = $true)]
|
[Parameter(Mandatory = $true)]
|
||||||
[string]$Target)
|
[string]$Target)
|
||||||
|
|
||||||
# This script translates the output from 7zdec into UTF8. Node has limited
|
# This script translates the output from 7zdec into UTF8. Node has limited
|
||||||
# built-in support for encodings.
|
# built-in support for encodings.
|
||||||
#
|
#
|
||||||
# 7zdec uses the system default code page. The system default code page varies
|
# 7zdec uses the system default code page. The system default code page varies
|
||||||
# depending on the locale configuration. On an en-US box, the system default code
|
# depending on the locale configuration. On an en-US box, the system default code
|
||||||
# page is Windows-1252.
|
# page is Windows-1252.
|
||||||
#
|
#
|
||||||
# Note, on a typical en-US box, testing with the 'ç' character is a good way to
|
# Note, on a typical en-US box, testing with the 'ç' character is a good way to
|
||||||
# determine whether data is passed correctly between processes. This is because
|
# determine whether data is passed correctly between processes. This is because
|
||||||
# the 'ç' character has a different code point across each of the common encodings
|
# the 'ç' character has a different code point across each of the common encodings
|
||||||
# on a typical en-US box, i.e.
|
# on a typical en-US box, i.e.
|
||||||
# 1) the default console-output code page (IBM437)
|
# 1) the default console-output code page (IBM437)
|
||||||
# 2) the system default code page (i.e. CP_ACP) (Windows-1252)
|
# 2) the system default code page (i.e. CP_ACP) (Windows-1252)
|
||||||
# 3) UTF8
|
# 3) UTF8
|
||||||
|
|
||||||
$ErrorActionPreference = 'Stop'
|
$ErrorActionPreference = 'Stop'
|
||||||
|
|
||||||
# Redefine the wrapper over STDOUT to use UTF8. Node expects UTF8 by default.
|
# Redefine the wrapper over STDOUT to use UTF8. Node expects UTF8 by default.
|
||||||
$stdout = [System.Console]::OpenStandardOutput()
|
$stdout = [System.Console]::OpenStandardOutput()
|
||||||
$utf8 = New-Object System.Text.UTF8Encoding($false) # do not emit BOM
|
$utf8 = New-Object System.Text.UTF8Encoding($false) # do not emit BOM
|
||||||
$writer = New-Object System.IO.StreamWriter($stdout, $utf8)
|
$writer = New-Object System.IO.StreamWriter($stdout, $utf8)
|
||||||
[System.Console]::SetOut($writer)
|
[System.Console]::SetOut($writer)
|
||||||
|
|
||||||
# All subsequent output must be written using [System.Console]::WriteLine(). In
|
# All subsequent output must be written using [System.Console]::WriteLine(). In
|
||||||
# PowerShell 4, Write-Host and Out-Default do not consider the updated stream writer.
|
# PowerShell 4, Write-Host and Out-Default do not consider the updated stream writer.
|
||||||
|
|
||||||
Set-Location -LiteralPath $Target
|
Set-Location -LiteralPath $Target
|
||||||
|
|
||||||
# Print the ##command.
|
# Print the ##command.
|
||||||
$_7zdec = Join-Path -Path "$PSScriptRoot" -ChildPath "externals/7zdec.exe"
|
$_7zdec = Join-Path -Path "$PSScriptRoot" -ChildPath "externals/7zdec.exe"
|
||||||
[System.Console]::WriteLine("##[command]$_7zdec x `"$Source`"")
|
[System.Console]::WriteLine("##[command]$_7zdec x `"$Source`"")
|
||||||
|
|
||||||
# The $OutputEncoding variable instructs PowerShell how to interpret the output
|
# The $OutputEncoding variable instructs PowerShell how to interpret the output
|
||||||
# from the external command.
|
# from the external command.
|
||||||
$OutputEncoding = [System.Text.Encoding]::Default
|
$OutputEncoding = [System.Text.Encoding]::Default
|
||||||
|
|
||||||
# Note, the output from 7zdec.exe needs to be iterated over. Otherwise PowerShell.exe
|
# Note, the output from 7zdec.exe needs to be iterated over. Otherwise PowerShell.exe
|
||||||
# will launch the external command in such a way that it inherits the streams.
|
# will launch the external command in such a way that it inherits the streams.
|
||||||
& $_7zdec x $Source 2>&1 |
|
& $_7zdec x $Source 2>&1 |
|
||||||
ForEach-Object {
|
ForEach-Object {
|
||||||
if ($_ -is [System.Management.Automation.ErrorRecord]) {
|
if ($_ -is [System.Management.Automation.ErrorRecord]) {
|
||||||
[System.Console]::WriteLine($_.Exception.Message)
|
[System.Console]::WriteLine($_.Exception.Message)
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
[System.Console]::WriteLine($_)
|
[System.Console]::WriteLine($_)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
[System.Console]::WriteLine("##[debug]7zdec.exe exit code '$LASTEXITCODE'")
|
[System.Console]::WriteLine("##[debug]7zdec.exe exit code '$LASTEXITCODE'")
|
||||||
[System.Console]::Out.Flush()
|
[System.Console]::Out.Flush()
|
||||||
if ($LASTEXITCODE -ne 0) {
|
if ($LASTEXITCODE -ne 0) {
|
||||||
exit $LASTEXITCODE
|
exit $LASTEXITCODE
|
||||||
}
|
}
|
||||||
Binary file not shown.
@ -1 +0,0 @@
|
|||||||
|
|
||||||
@ -1,274 +0,0 @@
|
|||||||
3.12.20 / 2019-08-16
|
|
||||||
* Revert: Fix #167: '>' in attribute value as it is causing high performance degrade.
|
|
||||||
3.12.19 / 2019-07-28
|
|
||||||
* Fix js to xml parser should work for date values. (broken: `tagValueProcessor` will receive the original value instead of string always) (breaking change)
|
|
||||||
3.12.18 / 2019-07-27
|
|
||||||
* remove configstore dependency
|
|
||||||
3.12.17 / 2019-07-14
|
|
||||||
* Fix #167: '>' in attribute value
|
|
||||||
3.12.16 / 2019-03-23
|
|
||||||
* Support a new option "stopNodes". (#150)
|
|
||||||
|
|
||||||
Accept the list of tags which are not required to be parsed. Instead, all the nested tag and data will be assigned as string.
|
|
||||||
* Don't show post-install message
|
|
||||||
3.12.12 / 2019-01-11
|
|
||||||
* fix : IE parseInt, parseFloat error
|
|
||||||
3.12.11 / 2018-12-24
|
|
||||||
* fix #132: "/" should not be parsed as boolean attr in case of self closing tags
|
|
||||||
3.12.9 / 2018-11-23
|
|
||||||
* fix #129 : validator should not fail when an atrribute name is 'length'
|
|
||||||
3.12.8 / 2018-11-22
|
|
||||||
* fix #128 : use 'attrValueProcessor' to process attribute value in json2xml parser
|
|
||||||
3.12.6 / 2018-11-10
|
|
||||||
* Fix #126: check for type
|
|
||||||
3.12.4 / 2018-09-12
|
|
||||||
* Fix: include tasks in npm package
|
|
||||||
3.12.3 / 2018-09-12
|
|
||||||
* Fix CLI issue raised in last PR
|
|
||||||
3.12.2 / 2018-09-11
|
|
||||||
* Fix formatting for JSON to XML output
|
|
||||||
* Migrate to webpack (PR merged)
|
|
||||||
* fix cli (PR merged)
|
|
||||||
3.12.0 / 2018-08-06
|
|
||||||
* Support hexadecimal values
|
|
||||||
* Support true number parsing
|
|
||||||
3.11.2 / 2018-07-23
|
|
||||||
* Update Demo for more options
|
|
||||||
* Update license information
|
|
||||||
* Update readme for formatting, users, and spelling mistakes
|
|
||||||
* Add missing typescript definition for j2xParser
|
|
||||||
* refactoring: change filenames
|
|
||||||
3.11.1 / 2018-06-05
|
|
||||||
* fix #93: read the text after self closing tag
|
|
||||||
3.11.0 / 2018-05-20
|
|
||||||
* return defaultOptions if there are not options in buildOptions function
|
|
||||||
* added localeRange declaration in parser.d.ts
|
|
||||||
* Added support of cyrillic characters in validator XML
|
|
||||||
* fixed bug in validator work when XML data with byte order marker
|
|
||||||
3.10.0 / 2018-05-13
|
|
||||||
* Added support of cyrillic characters in parsing XML to JSON
|
|
||||||
3.9.11 / 2018-05-09
|
|
||||||
* fix https://github.com/NaturalIntelligence/fast-xml-parser/issues/80 fix nimn chars
|
|
||||||
* update package information
|
|
||||||
* fix https://github.com/NaturalIntelligence/fast-xml-parser/issues/86: json 2 xml parser : property with null value should be parsed to self closing tag.
|
|
||||||
* update online demo
|
|
||||||
* revert zombiejs to old version to support old version of node
|
|
||||||
* update dependencies
|
|
||||||
3.3.10 / 2018-04-23
|
|
||||||
* fix #77 : parse even if closing tag has space before '>'
|
|
||||||
* include all css & js lib in demo app
|
|
||||||
* remove babel dependencies until needed
|
|
||||||
3.3.9 / 2018-04-18
|
|
||||||
* fix #74 : TS2314 TypeScript compiler error
|
|
||||||
3.3.8 / 2018-04-17
|
|
||||||
* fix #73 : IE doesn't support Object.assign
|
|
||||||
3.3.7 / 2018-04-14
|
|
||||||
* fix: use let insted of const in for loop of validator
|
|
||||||
* Merge pull request
|
|
||||||
https://github.com/NaturalIntelligence/fast-xml-parser/issues/71 from bb/master
|
|
||||||
first draft of typings for typescript
|
|
||||||
https://github.com/NaturalIntelligence/fast-xml-parser/issues/69
|
|
||||||
* Merge pull request
|
|
||||||
https://github.com/NaturalIntelligence/fast-xml-parser/issues/70 from bb/patch-1
|
|
||||||
fix some typos in readme
|
|
||||||
3.3.6 / 2018-03-21
|
|
||||||
* change arrow functions to full notation for IE compatibility
|
|
||||||
3.3.5 / 2018-03-15
|
|
||||||
* fix https://github.com/NaturalIntelligence/fast-xml-parser/issues/67 : attrNodeName invalid behavior
|
|
||||||
* fix: remove decodeHTML char condition
|
|
||||||
3.3.4 / 2018-03-14
|
|
||||||
* remove dependency on "he" package
|
|
||||||
* refactor code to separate methods in separate files.
|
|
||||||
* draft code for transforming XML to json string. It is not officially documented due to performance issue.
|
|
||||||
3.3.0 / 2018-03-05
|
|
||||||
* use common default options for XML parsing for consistency. And add `parseToNimn` method.
|
|
||||||
* update nexttodo
|
|
||||||
* update README about XML to Nimn transformation and remove special notes about 3.x release
|
|
||||||
* update CONTRIBUTING.ms mentioning nexttodo
|
|
||||||
* add negative case for XML PIs
|
|
||||||
* validate xml processing instruction tags https://github.com/NaturalIntelligence/fast-xml-parser/issues/62
|
|
||||||
* nimndata: handle array with object
|
|
||||||
* nimndata: node with nested node and text node
|
|
||||||
* nimndata: handle attributes and text node
|
|
||||||
* nimndata: add options, handle array
|
|
||||||
* add xml to nimn data converter
|
|
||||||
* x2j: direct access property with tagname
|
|
||||||
* update changelog
|
|
||||||
* fix validator when single quote presents in value enclosed with double quotes or vice versa
|
|
||||||
* Revert "remove unneded nimnjs dependency, move opencollective to devDependencies and replace it
|
|
||||||
with more light opencollective-postinstall"
|
|
||||||
This reverts commit d47aa7181075d82db4fee97fd8ea32b056fe3f46.
|
|
||||||
* Merge pull request: https://github.com/NaturalIntelligence/fast-xml-parser/issues/63 from HaroldPutman/suppress-undefined
|
|
||||||
Keep undefined nodes out of the XML output : This is useful when you are deleting nodes from the JSON and rewriting XML.
|
|
||||||
3.2.4 / 2018-03-01
|
|
||||||
* fix #59 fix in validator when open quote presents in attribute value
|
|
||||||
* Create nexttodo.md
|
|
||||||
* exclude static from bitHound tests
|
|
||||||
* add package lock
|
|
||||||
3.2.3 / 2018-02-28
|
|
||||||
* Merge pull request from Delagen/master: fix namespaces can contain the same characters as xml names
|
|
||||||
3.2.2 / 2018-02-22
|
|
||||||
* fix: attribute xmlns should not be removed if ignoreNameSpace is false
|
|
||||||
* create CONTRIBUTING.md
|
|
||||||
3.2.1 / 2018-02-17
|
|
||||||
* fix: empty attribute should be parsed
|
|
||||||
3.2.0 / 2018-02-16
|
|
||||||
* Merge pull request : Dev to Master
|
|
||||||
* Update README and version
|
|
||||||
* j2x:add performance test
|
|
||||||
* j2x: Remove extra empty line before closing tag
|
|
||||||
* j2x: suppress empty nodes to self closing node if configured
|
|
||||||
* j2x: provide option to give indentation depth
|
|
||||||
* j2x: make optional formatting
|
|
||||||
* j2x: encodeHTMLchat
|
|
||||||
* j2x: handle cdata tag
|
|
||||||
* j2x: handle grouped attributes
|
|
||||||
* convert json to xml
|
|
||||||
- nested object
|
|
||||||
- array
|
|
||||||
- attributes
|
|
||||||
- text value
|
|
||||||
* small refactoring
|
|
||||||
* Merge pull request: Update cli.js to let user validate XML file or data
|
|
||||||
* Add option for rendering CDATA as separate property
|
|
||||||
3.0.1 / 2018-02-09
|
|
||||||
* fix CRLF: replace it with single space in attributes value only.
|
|
||||||
3.0.0 / 2018-02-08
|
|
||||||
* change online tool with new changes
|
|
||||||
* update info about new options
|
|
||||||
* separate tag value processing to separate function
|
|
||||||
* make HTML decoding optional
|
|
||||||
* give an option to allow boolean attributes
|
|
||||||
* change cli options as per v3
|
|
||||||
* Correct comparison table format on README
|
|
||||||
* update v3 information
|
|
||||||
* some performance improvement changes
|
|
||||||
* Make regex object local to the method and move some common methods to util
|
|
||||||
* Change parser to
|
|
||||||
- handle multiple instances of CDATA
|
|
||||||
- make triming of value optionals
|
|
||||||
- HTML decode attribute and text value
|
|
||||||
- refactor code to separate files
|
|
||||||
* Ignore newline chars without RE (in validator)
|
|
||||||
* validate for XML prolog
|
|
||||||
* Validate DOCTYPE without RE
|
|
||||||
* Update validator to return error response
|
|
||||||
* Update README to add detail about V3
|
|
||||||
* Separate xmlNode model class
|
|
||||||
* include vscode debug config
|
|
||||||
* fix for repeated object
|
|
||||||
* fix attribute regex for boolean attributes
|
|
||||||
* Fix validator for invalid attributes
|
|
||||||
2.9.4 / 2018-02-02
|
|
||||||
* Merge pull request: Decode HTML characters
|
|
||||||
* refactor source folder name
|
|
||||||
* ignore bundle / browser js to be published to npm
|
|
||||||
2.9.3 / 2018-01-26
|
|
||||||
* Merge pull request: Correctly remove CRLF line breaks
|
|
||||||
* Enable to parse attribute in online editor
|
|
||||||
* Fix testing demo app test
|
|
||||||
* Describe parsing options
|
|
||||||
* Add options for online demo
|
|
||||||
2.9.2 / 2018-01-18
|
|
||||||
* Remove check if tag starting with "XML"
|
|
||||||
* Fix: when there are spaces before / after CDATA
|
|
||||||
|
|
||||||
2.9.1 / 2018-01-16
|
|
||||||
* Fix: newline should be replaced with single space
|
|
||||||
* Fix: for single and multiline comments
|
|
||||||
* validate xml with CDATA
|
|
||||||
* Fix: the issue when there is no space between 2 attributes
|
|
||||||
* Fix: https://github.com/NaturalIntelligence/fast-xml-parser/issues/33: when there is newline char in attr val, it doesn't parse
|
|
||||||
* Merge pull request: fix ignoreNamespace
|
|
||||||
* fix: don't wrap attributes if only namespace attrs
|
|
||||||
* fix: use portfinder for run tests, update deps
|
|
||||||
* fix: don't treat namespaces as attributes when ignoreNamespace enabled
|
|
||||||
|
|
||||||
2.9.0 / 2018-01-10
|
|
||||||
* Rewrite the validator to handle large files.
|
|
||||||
Ignore DOCTYPE validation.
|
|
||||||
* Fix: When attribute value has equal sign
|
|
||||||
|
|
||||||
2.8.3 / 2017-12-15
|
|
||||||
* Fix: when a tag has value along with subtags
|
|
||||||
|
|
||||||
2.8.2 / 2017-12-04
|
|
||||||
* Fix value parsing for IE
|
|
||||||
|
|
||||||
2.8.1 / 2017-12-01
|
|
||||||
* fix: validator should return false instead of err when invalid XML
|
|
||||||
|
|
||||||
2.8.0 / 2017-11-29
|
|
||||||
* Add CLI option to ignore value conversion
|
|
||||||
* Fix variable name when filename is given on CLI
|
|
||||||
* Update CLI help text
|
|
||||||
* Merge pull request: xml2js: Accept standard input
|
|
||||||
* Test Node 8
|
|
||||||
* Update dependencies
|
|
||||||
* Bundle readToEnd
|
|
||||||
* Add ability to read from standard input
|
|
||||||
|
|
||||||
2.7.4 / 2017-09-22
|
|
||||||
* Merge pull request: Allow wrap attributes with subobject to compatible with other parsers output
|
|
||||||
|
|
||||||
2.7.3 / 2017-08-02
|
|
||||||
* fix: handle CDATA with regx
|
|
||||||
|
|
||||||
2.7.2 / 2017-07-30
|
|
||||||
* Change travis config for yarn caching
|
|
||||||
* fix validator: when tag property is same as array property
|
|
||||||
* Merge pull request: Failing test case in validator for valid SVG
|
|
||||||
|
|
||||||
2.7.1 / 2017-07-26
|
|
||||||
* Fix: Handle val 0
|
|
||||||
|
|
||||||
2.7.0 / 2017-07-25
|
|
||||||
* Fix test for arrayMode
|
|
||||||
* Merge pull request: Add arrayMode option to parse any nodes as arrays
|
|
||||||
|
|
||||||
2.6.0 / 2017-07-14
|
|
||||||
* code improvement
|
|
||||||
* Add unit tests for value conversion for attr
|
|
||||||
* Merge pull request: option of an attribute value conversion to a number (textAttrConversion) the same way as the textNodeConversion option does. Default value is false.
|
|
||||||
|
|
||||||
2.5.1 / 2017-07-01
|
|
||||||
* Fix XML element name pattern
|
|
||||||
* Fix XML element name pattern while parsing
|
|
||||||
* Fix validation for xml tag element
|
|
||||||
|
|
||||||
2.5.0 / 2017-06-25
|
|
||||||
* Improve Validator performance
|
|
||||||
* update attr matching regex
|
|
||||||
* Add perf tests
|
|
||||||
* Improve atrr regex to handle all cases
|
|
||||||
|
|
||||||
2.4.4 / 2017-06-08
|
|
||||||
* Bug fix: when an attribute has single or double quote in value
|
|
||||||
|
|
||||||
2.4.3 / 2017-06-05
|
|
||||||
* Bug fix: when multiple CDATA tags are given
|
|
||||||
* Merge pull request: add option "textNodeConversion"
|
|
||||||
* add option "textNodeConversion"
|
|
||||||
|
|
||||||
2.4.1 / 2017-04-14
|
|
||||||
* fix tests
|
|
||||||
* Bug fix: preserve initial space of node value
|
|
||||||
* Handle CDATA
|
|
||||||
|
|
||||||
2.3.1 / 2017-03-15
|
|
||||||
* Bug fix: when single self closing tag
|
|
||||||
* Merge pull request: fix .codeclimate.yml
|
|
||||||
* Update .codeclimate.yml - Fixed config so it does not error anymore.
|
|
||||||
* Update .codeclimate.yml
|
|
||||||
|
|
||||||
2.3.0 / 2017-02-26
|
|
||||||
* Code improvement
|
|
||||||
* add bithound config
|
|
||||||
* Update usage
|
|
||||||
* Update travis to generate bundle js before running tests
|
|
||||||
* 1.Browserify, 2. add more tests for validator
|
|
||||||
* Add validator
|
|
||||||
* Fix CLI default parameter bug
|
|
||||||
|
|
||||||
2.2.1 / 2017-02-05
|
|
||||||
* Bug fix: CLI default option
|
|
||||||
@ -1,46 +0,0 @@
|
|||||||
# Thanks
|
|
||||||
I would like to thank you for your valuable time and effort and applogies if this PR is rejected due to any reason.
|
|
||||||
|
|
||||||
This repository is written with the aim of providing high performance not in terms of speed only but comfortability of the user as well.
|
|
||||||
|
|
||||||
If your change is not a bug fix please check **nexttodo.md** before implementing any new feature.
|
|
||||||
|
|
||||||
## No rights are resserved
|
|
||||||
|
|
||||||
Your contribution is valuable. We try to mention your name on README with the avatar. We can't promise to pay you for your contribution.
|
|
||||||
|
|
||||||
### DoD
|
|
||||||
Here is the check list to publish any change
|
|
||||||
|
|
||||||
* Changes are not half implemented due to the library limitation or any other reason.
|
|
||||||
* Changes are well discussed by raising github issue. So they are well known by other contributers and users
|
|
||||||
* Echoing the above point. The purpose / goal for the PR should be mentioned in the description.
|
|
||||||
* Multiple unrelated changes should not be clubbed in single PR.
|
|
||||||
* Please run perf tests `node benchmark\perfTest3.js` before and after the changes. And mention it in PR description.
|
|
||||||
* If you are adding any dependency (specially if it is not the dev dependency) please check that
|
|
||||||
* it is not dependent on other language packages like c/c++
|
|
||||||
* the package is not very old, very new, discontinued, or has any vulnerability etc.
|
|
||||||
* please check the performance and size of package
|
|
||||||
* please check alternate available options
|
|
||||||
* Please write tests for the new changes
|
|
||||||
* Don't forget to write tests for negative cases
|
|
||||||
* Don't comment existing test case.
|
|
||||||
|
|
||||||
Changes need to do be done by owner
|
|
||||||
* Increase the version number
|
|
||||||
* Update the change log & README if required
|
|
||||||
* Generate the browser bundle
|
|
||||||
* Release in github and publish to npm
|
|
||||||
|
|
||||||
Note that publishing changes or accepting any PR may take time. So please keep patience.
|
|
||||||
|
|
||||||
### Guidelines for first time contributors
|
|
||||||
|
|
||||||
* https://github.com/Roshanjossey/first-contributions
|
|
||||||
* **Don't stretch**. If you complete an issue in long time, there is a possibility that other developers finish their part and you face code conflicts which may increase code complexity for you. So it is always good to complete an issue ASAP.
|
|
||||||
* Please refrain to work on multiple issues marked with "first-timers-only" in the same repo. Ask and help your friends and colleagues to attempt rest issues.
|
|
||||||
* Please claim the issue and clear your doubts before raising PR. So other users will not start working on the same issue.
|
|
||||||
* Mention the issue number either in PR detail or in commit message.
|
|
||||||
* Keep increasing the level of challenge.
|
|
||||||
* Don't hesitate to question on github issue or on twitter.
|
|
||||||
|
|
||||||
@ -1,17 +0,0 @@
|
|||||||
{
|
|
||||||
"tests": "./spec/*_spec.js",
|
|
||||||
"timeout": 10000,
|
|
||||||
"output": "./output",
|
|
||||||
"helpers": {
|
|
||||||
"WebDriverIO": {
|
|
||||||
"url": "http://localhost",
|
|
||||||
"browser": "chrome"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"include": {
|
|
||||||
"I": "./steps_file.js"
|
|
||||||
},
|
|
||||||
"bootstrap": false,
|
|
||||||
"mocha": {},
|
|
||||||
"name": "fxp"
|
|
||||||
}
|
|
||||||
@ -1,8 +0,0 @@
|
|||||||
* check test coverage and write necessary tests
|
|
||||||
* validate XML stream data
|
|
||||||
* Fix jTox for json array. Not sure if a bug exist.
|
|
||||||
* generate separate and combined browser bundle for xml -> nimn, xml -> json , json -> xml
|
|
||||||
* Es6 to es5 migration without workaround.
|
|
||||||
* Parse JSON string to XML. Currently it transforms JSON object to XML. Partially done. Need to work on performance.
|
|
||||||
* build properties only once
|
|
||||||
* XML to JSON ML : https://en.wikipedia.org/wiki/JsonML
|
|
||||||
File diff suppressed because it is too large
Load Diff
@ -1,16 +0,0 @@
|
|||||||
{
|
|
||||||
"version": "0.2.0",
|
|
||||||
"configurations": [
|
|
||||||
{
|
|
||||||
"type": "node",
|
|
||||||
"request": "launch",
|
|
||||||
"name": "Jasmine Tests",
|
|
||||||
"program": "${workspaceFolder}/node_modules/jasmine/bin/jasmine.js",
|
|
||||||
"args": [
|
|
||||||
"${workspaceFolder}/test/dateparser_test.js"
|
|
||||||
],
|
|
||||||
"internalConsoleOptions": "openOnSessionStart"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
|
|
||||||
}
|
|
||||||
@ -1,21 +0,0 @@
|
|||||||
MIT License
|
|
||||||
|
|
||||||
Copyright (c) 2018
|
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
||||||
of this software and associated documentation files (the "Software"), to deal
|
|
||||||
in the Software without restriction, including without limitation the rights
|
|
||||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
||||||
copies of the Software, and to permit persons to whom the Software is
|
|
||||||
furnished to do so, subject to the following conditions:
|
|
||||||
|
|
||||||
The above copyright notice and this permission notice shall be included in all
|
|
||||||
copies or substantial portions of the Software.
|
|
||||||
|
|
||||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
||||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
||||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
||||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
||||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
||||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
||||||
SOFTWARE.
|
|
||||||
@ -1,139 +0,0 @@
|
|||||||
var monthInitials = ["J","F","M","A","m","j","U","a","S","O","N","D"];
|
|
||||||
|
|
||||||
var initials = ["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
|
|
||||||
var timeZone = [
|
|
||||||
12*60,
|
|
||||||
11*60,
|
|
||||||
10*60,
|
|
||||||
9.5*60,
|
|
||||||
9*60,
|
|
||||||
8*60,
|
|
||||||
7*60,
|
|
||||||
6*60,
|
|
||||||
5*60,
|
|
||||||
4*60,
|
|
||||||
3.5*60,
|
|
||||||
3*60,
|
|
||||||
2*60,
|
|
||||||
1*60,
|
|
||||||
0*60,
|
|
||||||
-1*60,
|
|
||||||
-2*60,
|
|
||||||
-3*60,
|
|
||||||
-3.5*60,
|
|
||||||
-4*60,
|
|
||||||
-4.5*60,
|
|
||||||
-5*60,
|
|
||||||
-5.5*60,
|
|
||||||
-5.75*60,
|
|
||||||
-6*60,
|
|
||||||
-6.5*60,
|
|
||||||
-7*60,
|
|
||||||
-8*60,
|
|
||||||
-8.5*60,
|
|
||||||
-8.75*60,
|
|
||||||
-9*60,
|
|
||||||
-9.5*60,
|
|
||||||
-10*60,
|
|
||||||
-10.5*60,
|
|
||||||
-11*60,
|
|
||||||
-12*60,
|
|
||||||
-12.75*60,
|
|
||||||
-13*60,
|
|
||||||
-14*60
|
|
||||||
];
|
|
||||||
|
|
||||||
function parseToUTC(dtObj, includeDate, includeCentury, includeTime){
|
|
||||||
if(typeof dtObj === "string"){
|
|
||||||
dtObj = new Date(dtObj);
|
|
||||||
}
|
|
||||||
var dtStr = "";
|
|
||||||
if(includeCentury){
|
|
||||||
dtStr += char(Math.floor(dtObj.getUTCFullYear()/100)) ;
|
|
||||||
}
|
|
||||||
if(includeDate){//3
|
|
||||||
//year
|
|
||||||
dtStr += char(dtObj.getUTCFullYear()%100);
|
|
||||||
//month
|
|
||||||
dtStr += monthInitials[dtObj.getUTCMonth()];
|
|
||||||
//date
|
|
||||||
dtStr += initials[dtObj.getUTCDate()]
|
|
||||||
}
|
|
||||||
|
|
||||||
if(includeTime){//5
|
|
||||||
//h
|
|
||||||
dtStr += initials[dtObj.getUTCHours()]
|
|
||||||
//m
|
|
||||||
dtStr += initials[dtObj.getUTCMinutes()];
|
|
||||||
//s
|
|
||||||
dtStr += initials[dtObj.getUTCSeconds()];
|
|
||||||
//ms
|
|
||||||
var ms = dtObj.getUTCMilliseconds();
|
|
||||||
dtStr += char(Math.floor(ms/10)) ;
|
|
||||||
dtStr += char(ms%10) ;
|
|
||||||
}
|
|
||||||
|
|
||||||
//zone
|
|
||||||
//if(includeZone){//1
|
|
||||||
dtStr += initials[timeZone.indexOf(dtObj.getTimezoneOffset() ) ]
|
|
||||||
//}
|
|
||||||
return dtStr;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
*
|
|
||||||
* @param {*} dtStr
|
|
||||||
* @param {*} includeDate
|
|
||||||
* @param {*} includeCentury
|
|
||||||
* @param {*} includeTime
|
|
||||||
* @param {*} includeZone
|
|
||||||
*/
|
|
||||||
function parseBackUTC(dtStr,includeDate, includeCentury, includeTime){
|
|
||||||
|
|
||||||
var century = 0;
|
|
||||||
var startFrom = 0;
|
|
||||||
var Y = 0, M = 0, D = 0, h = 0, m = 0, s = 0, ms = 0, z = 0;
|
|
||||||
if(includeCentury){//1st digit is century
|
|
||||||
century = 100 * ascii(dtStr[startFrom++]);
|
|
||||||
}
|
|
||||||
|
|
||||||
if(includeDate){
|
|
||||||
Y = century + ascii(dtStr[startFrom++]);
|
|
||||||
M = monthInitials.indexOf(dtStr[startFrom++]);
|
|
||||||
D = initials.indexOf(dtStr[startFrom++])
|
|
||||||
//startFrom += 3;
|
|
||||||
}
|
|
||||||
|
|
||||||
if(includeTime){
|
|
||||||
h = initials.indexOf(dtStr[startFrom++]);
|
|
||||||
m = initials.indexOf(dtStr[startFrom++]);
|
|
||||||
s = initials.indexOf(dtStr[startFrom++]);
|
|
||||||
|
|
||||||
ms = ascii(dtStr[startFrom++])*10 + ascii(dtStr[startFrom++]);
|
|
||||||
//startFrom += 5;
|
|
||||||
}
|
|
||||||
var dt = new Date(Y,M,D,h,m,s,ms);
|
|
||||||
//if(includeZone){
|
|
||||||
z = timeZone[initials.indexOf(dtStr[startFrom])];
|
|
||||||
dt.setTime(dt.getTime() - z*60*1000);
|
|
||||||
//}
|
|
||||||
|
|
||||||
return dt;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
function ascii(ch){
|
|
||||||
return ch.charCodeAt(0);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* converts a ASCII number into equivalant ASCII char
|
|
||||||
* @param {number} a
|
|
||||||
* @returns ASCII char
|
|
||||||
*/
|
|
||||||
var char = function (a){
|
|
||||||
return String.fromCharCode(a);
|
|
||||||
}
|
|
||||||
|
|
||||||
exports.parse = parseToUTC;
|
|
||||||
exports.parseBack = parseBackUTC;
|
|
||||||
@ -1,63 +0,0 @@
|
|||||||
{
|
|
||||||
"_args": [
|
|
||||||
[
|
|
||||||
"nimn-date-parser@1.0.0",
|
|
||||||
"C:\\dev\\repos\\actions\\setup-dotnet"
|
|
||||||
]
|
|
||||||
],
|
|
||||||
"_from": "nimn-date-parser@1.0.0",
|
|
||||||
"_id": "nimn-date-parser@1.0.0",
|
|
||||||
"_inBundle": false,
|
|
||||||
"_integrity": "sha512-1Nf+x3EeMvHUiHsVuEhiZnwA8RMeOBVTQWfB1S2n9+i6PYCofHd2HRMD+WOHIHYshy4T4Gk8wQoCol7Hq3av8Q==",
|
|
||||||
"_location": "/nimn-date-parser",
|
|
||||||
"_phantomChildren": {},
|
|
||||||
"_requested": {
|
|
||||||
"type": "version",
|
|
||||||
"registry": true,
|
|
||||||
"raw": "nimn-date-parser@1.0.0",
|
|
||||||
"name": "nimn-date-parser",
|
|
||||||
"escapedName": "nimn-date-parser",
|
|
||||||
"rawSpec": "1.0.0",
|
|
||||||
"saveSpec": null,
|
|
||||||
"fetchSpec": "1.0.0"
|
|
||||||
},
|
|
||||||
"_requiredBy": [
|
|
||||||
"/nimnjs"
|
|
||||||
],
|
|
||||||
"_resolved": "https://registry.npmjs.org/nimn-date-parser/-/nimn-date-parser-1.0.0.tgz",
|
|
||||||
"_spec": "1.0.0",
|
|
||||||
"_where": "C:\\dev\\repos\\actions\\setup-dotnet",
|
|
||||||
"author": {
|
|
||||||
"name": "Amit Gupta",
|
|
||||||
"url": "https://github.com/amitguptagwl"
|
|
||||||
},
|
|
||||||
"bugs": {
|
|
||||||
"url": "https://github.com/nimndata/nimnjs-date-parser/issues"
|
|
||||||
},
|
|
||||||
"description": "Compress date for nimnjs",
|
|
||||||
"devDependencies": {
|
|
||||||
"jasmine": "^3.0.0",
|
|
||||||
"jasmine-core": "^2.99.1"
|
|
||||||
},
|
|
||||||
"directories": {
|
|
||||||
"test": "tests"
|
|
||||||
},
|
|
||||||
"homepage": "https://github.com/nimndata/nimnjs-date-parser#readme",
|
|
||||||
"keywords": [
|
|
||||||
"nimn",
|
|
||||||
"nimnjs",
|
|
||||||
"date",
|
|
||||||
"parser"
|
|
||||||
],
|
|
||||||
"license": "MIT",
|
|
||||||
"main": "dateparser.js",
|
|
||||||
"name": "nimn-date-parser",
|
|
||||||
"repository": {
|
|
||||||
"type": "git",
|
|
||||||
"url": "git+https://github.com/nimndata/nimnjs-date-parser.git"
|
|
||||||
},
|
|
||||||
"scripts": {
|
|
||||||
"test": "jasmine tests/*test.js"
|
|
||||||
},
|
|
||||||
"version": "1.0.0"
|
|
||||||
}
|
|
||||||
@ -1,72 +0,0 @@
|
|||||||
var parser = require("../dateparser.js");
|
|
||||||
|
|
||||||
describe("Date parser", function () {
|
|
||||||
it(" should parse and parseback full date", function () {
|
|
||||||
|
|
||||||
var dt = new Date("Mon Feb 26 2018 17:42:17 GMT+0530 (IST)");
|
|
||||||
//var dt = new Date("Tue May 15 2012 05:45:40 GMT-0500");
|
|
||||||
//console.log(dt);
|
|
||||||
|
|
||||||
var nimnDt = parser.parse(dt,true,true,true);
|
|
||||||
console.log(nimnDt);
|
|
||||||
|
|
||||||
var dt2 = parser.parseBack(nimnDt,true,true,true);
|
|
||||||
//console.log(dt2);
|
|
||||||
|
|
||||||
expect(dt).toEqual(dt2);
|
|
||||||
expect(10).toEqual(nimnDt.length);
|
|
||||||
|
|
||||||
});
|
|
||||||
|
|
||||||
it(" should parse and parseback only date part", function () {
|
|
||||||
|
|
||||||
var dt = new Date();
|
|
||||||
//console.log(dt);
|
|
||||||
|
|
||||||
var nimnDt = parser.parse(dt,true,false);
|
|
||||||
//console.log(nimnDt);
|
|
||||||
|
|
||||||
var dt2 = parser.parseBack(nimnDt,true,false);
|
|
||||||
//console.log(dt2);
|
|
||||||
|
|
||||||
expect(4).toEqual(nimnDt.length);
|
|
||||||
expect(dt.getFullYear()%100).toEqual(dt2.getFullYear()%100);
|
|
||||||
expect(dt.getMonth()).toEqual(dt2.getMonth());
|
|
||||||
expect(dt.getDate()).toEqual(dt2.getDate());
|
|
||||||
|
|
||||||
});
|
|
||||||
|
|
||||||
it(" should parse and parseback date part with century", function () {
|
|
||||||
var dt = new Date();
|
|
||||||
//console.log(dt);
|
|
||||||
|
|
||||||
var nimnDt = parser.parse(dt,true,true);
|
|
||||||
//console.log(nimnDt);
|
|
||||||
|
|
||||||
var dt2 = parser.parseBack(nimnDt,true,true);
|
|
||||||
//console.log(dt2);
|
|
||||||
|
|
||||||
expect(5).toEqual(nimnDt.length);
|
|
||||||
expect(dt.getFullYear()).toEqual(dt2.getFullYear());
|
|
||||||
expect(dt.getMonth()).toEqual(dt2.getMonth());
|
|
||||||
expect(dt.getDate()).toEqual(dt2.getDate());
|
|
||||||
});
|
|
||||||
|
|
||||||
it(" should parse and parseback time", function () {
|
|
||||||
var dt = new Date();
|
|
||||||
//console.log(dt);
|
|
||||||
|
|
||||||
var nimnDt = parser.parse(dt,false,false,true);
|
|
||||||
//console.log(nimnDt);
|
|
||||||
|
|
||||||
var dt2 = parser.parseBack(nimnDt,false,false,true);
|
|
||||||
//console.log(dt2);
|
|
||||||
|
|
||||||
expect(6).toEqual(nimnDt.length);
|
|
||||||
expect(dt.getHours()).toEqual(dt2.getHours());
|
|
||||||
expect(dt.getMinutes()).toEqual(dt2.getMinutes());
|
|
||||||
expect(dt.getSeconds()).toEqual(dt2.getSeconds());
|
|
||||||
expect(dt.getMilliseconds()).toEqual(dt2.getMilliseconds());
|
|
||||||
});
|
|
||||||
|
|
||||||
});
|
|
||||||
@ -1,21 +0,0 @@
|
|||||||
MIT License
|
|
||||||
|
|
||||||
Copyright (c) 2018
|
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
||||||
of this software and associated documentation files (the "Software"), to deal
|
|
||||||
in the Software without restriction, including without limitation the rights
|
|
||||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
||||||
copies of the Software, and to permit persons to whom the Software is
|
|
||||||
furnished to do so, subject to the following conditions:
|
|
||||||
|
|
||||||
The above copyright notice and this permission notice shall be included in all
|
|
||||||
copies or substantial portions of the Software.
|
|
||||||
|
|
||||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
||||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
||||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
||||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
||||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
||||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
||||||
SOFTWARE.
|
|
||||||
@ -1,49 +0,0 @@
|
|||||||
# nimnjs-schema-builder
|
|
||||||
Build schema from JS object or JSON to feed into [nimnjs](https://github.com/nimndata/nimnjs-node).
|
|
||||||
|
|
||||||
|
|
||||||
## Usages
|
|
||||||
|
|
||||||
First install or add to your npm package
|
|
||||||
```
|
|
||||||
$npm install nimn_schema_builder
|
|
||||||
```
|
|
||||||
|
|
||||||
```js
|
|
||||||
var builder = require("nimn_schema_builder");
|
|
||||||
|
|
||||||
var data = {
|
|
||||||
name : "amit",
|
|
||||||
age : 32,
|
|
||||||
human : true,
|
|
||||||
projects : [
|
|
||||||
{
|
|
||||||
name: "some",
|
|
||||||
from: new Date(),
|
|
||||||
//to: null,
|
|
||||||
decription : "some long description"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
|
|
||||||
var schema = builder.build(data);
|
|
||||||
|
|
||||||
/*
|
|
||||||
var schema = {
|
|
||||||
name : "string",
|
|
||||||
age : "number",
|
|
||||||
human : "boolean",
|
|
||||||
projects : [
|
|
||||||
{
|
|
||||||
name: "string",
|
|
||||||
from: "date",
|
|
||||||
decription : "string"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
};
|
|
||||||
*/
|
|
||||||
```
|
|
||||||
|
|
||||||
You can also use it in browser from [dist](dist/nimn-schema-builder.js) folder.
|
|
||||||
|
|
||||||
Check the [demo](https://nimndata.github.io/nimnjs-schema-builder/) for instant use.
|
|
||||||
@ -1,44 +0,0 @@
|
|||||||
|
|
||||||
/**
|
|
||||||
* Build Schema for nimnification of JSON data
|
|
||||||
* @param {*} jsObj
|
|
||||||
*/
|
|
||||||
function buildSchema(jsObj){
|
|
||||||
var type = typeOf(jsObj);
|
|
||||||
switch(type){
|
|
||||||
case "array":
|
|
||||||
return [buildSchema(jsObj[0])];
|
|
||||||
case "object":
|
|
||||||
var schema = { };
|
|
||||||
var keys = Object.keys(jsObj);
|
|
||||||
for(var i in keys){
|
|
||||||
var key = keys[i];
|
|
||||||
/* if(key === null || typeof key === "undefined"){//in case of null or undefined, take sibling's type
|
|
||||||
if(keys[i+1] ){
|
|
||||||
schema[key] = buildSchema(jsObj[keys[i+1]]);
|
|
||||||
}else if(keys[i-1]){
|
|
||||||
schema[key] = buildSchema(jsObj[keys[i-1]]);
|
|
||||||
}
|
|
||||||
continue;
|
|
||||||
} */
|
|
||||||
schema[key] = buildSchema(jsObj[key]);
|
|
||||||
}
|
|
||||||
return schema;
|
|
||||||
case "string":
|
|
||||||
case "number":
|
|
||||||
case "date":
|
|
||||||
case "boolean":
|
|
||||||
return type;
|
|
||||||
default:
|
|
||||||
throw Error("Unacceptable type : " + type);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function typeOf(obj){
|
|
||||||
if(obj === null) return "null";
|
|
||||||
else if(Array.isArray(obj)) return "array";
|
|
||||||
else if(obj instanceof Date) return "date";
|
|
||||||
else return typeof obj;
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports.build = buildSchema;
|
|
||||||
@ -1,47 +0,0 @@
|
|||||||
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.nimnSchemaBuilder = f()}})(function(){var define,module,exports;return (function(){function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}return e})()({1:[function(require,module,exports){
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Build Schema for nimnification of JSON data
|
|
||||||
* @param {*} jsObj
|
|
||||||
*/
|
|
||||||
function buildSchema(jsObj){
|
|
||||||
var type = typeOf(jsObj);
|
|
||||||
switch(type){
|
|
||||||
case "array":
|
|
||||||
return [buildSchema(jsObj[0])];
|
|
||||||
case "object":
|
|
||||||
var schema = { };
|
|
||||||
var keys = Object.keys(jsObj);
|
|
||||||
for(var i in keys){
|
|
||||||
var key = keys[i];
|
|
||||||
/* if(key === null || typeof key === "undefined"){//in case of null or undefined, take sibling's type
|
|
||||||
if(keys[i+1] ){
|
|
||||||
schema[key] = buildSchema(jsObj[keys[i+1]]);
|
|
||||||
}else if(keys[i-1]){
|
|
||||||
schema[key] = buildSchema(jsObj[keys[i-1]]);
|
|
||||||
}
|
|
||||||
continue;
|
|
||||||
} */
|
|
||||||
schema[key] = buildSchema(jsObj[key]);
|
|
||||||
}
|
|
||||||
return schema;
|
|
||||||
case "string":
|
|
||||||
case "number":
|
|
||||||
case "date":
|
|
||||||
case "boolean":
|
|
||||||
return type;
|
|
||||||
default:
|
|
||||||
throw Error("Unacceptable type : " + type);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function typeOf(obj){
|
|
||||||
if(obj === null) return "null";
|
|
||||||
else if(Array.isArray(obj)) return "array";
|
|
||||||
else if(obj instanceof Date) return "date";
|
|
||||||
else return typeof obj;
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports.build = buildSchema;
|
|
||||||
},{}]},{},[1])(1)
|
|
||||||
});
|
|
||||||
@ -1,59 +0,0 @@
|
|||||||
{
|
|
||||||
"_args": [
|
|
||||||
[
|
|
||||||
"nimn_schema_builder@1.1.0",
|
|
||||||
"C:\\dev\\repos\\actions\\setup-dotnet"
|
|
||||||
]
|
|
||||||
],
|
|
||||||
"_from": "nimn_schema_builder@1.1.0",
|
|
||||||
"_id": "nimn_schema_builder@1.1.0",
|
|
||||||
"_inBundle": false,
|
|
||||||
"_integrity": "sha512-DK5/B8CM4qwzG2URy130avcwPev4uO0ev836FbQyKo1ms6I9z/i6EJyiZ+d9xtgloxUri0W+5gfR8YbPq7SheA==",
|
|
||||||
"_location": "/nimn_schema_builder",
|
|
||||||
"_phantomChildren": {},
|
|
||||||
"_requested": {
|
|
||||||
"type": "version",
|
|
||||||
"registry": true,
|
|
||||||
"raw": "nimn_schema_builder@1.1.0",
|
|
||||||
"name": "nimn_schema_builder",
|
|
||||||
"escapedName": "nimn_schema_builder",
|
|
||||||
"rawSpec": "1.1.0",
|
|
||||||
"saveSpec": null,
|
|
||||||
"fetchSpec": "1.1.0"
|
|
||||||
},
|
|
||||||
"_requiredBy": [
|
|
||||||
"/nimnjs"
|
|
||||||
],
|
|
||||||
"_resolved": "https://registry.npmjs.org/nimn_schema_builder/-/nimn_schema_builder-1.1.0.tgz",
|
|
||||||
"_spec": "1.1.0",
|
|
||||||
"_where": "C:\\dev\\repos\\actions\\setup-dotnet",
|
|
||||||
"author": {
|
|
||||||
"name": "Amit Gupta",
|
|
||||||
"url": "https://github.com/amitguptagwl"
|
|
||||||
},
|
|
||||||
"bugs": {
|
|
||||||
"url": "https://github.com/nimndata/nimnjs-schema-builder/issues"
|
|
||||||
},
|
|
||||||
"description": "Build schema from JS object or JSON to feed into nimnjs",
|
|
||||||
"devDependencies": {
|
|
||||||
"browserify": "^16.1.0"
|
|
||||||
},
|
|
||||||
"homepage": "https://github.com/nimndata/nimnjs-schema-builder#readme",
|
|
||||||
"keywords": [
|
|
||||||
"nimn",
|
|
||||||
"nimnjs",
|
|
||||||
"builder",
|
|
||||||
"schema"
|
|
||||||
],
|
|
||||||
"license": "MIT",
|
|
||||||
"main": "builder.js",
|
|
||||||
"name": "nimn_schema_builder",
|
|
||||||
"repository": {
|
|
||||||
"type": "git",
|
|
||||||
"url": "git+https://github.com/nimndata/nimnjs-schema-builder.git"
|
|
||||||
},
|
|
||||||
"scripts": {
|
|
||||||
"bundle": "browserify builder.js -s nimn-schema-builder -o dist/nimn-schema-builder.js"
|
|
||||||
},
|
|
||||||
"version": "1.1.0"
|
|
||||||
}
|
|
||||||
@ -1,16 +0,0 @@
|
|||||||
{
|
|
||||||
"version": "0.2.0",
|
|
||||||
"configurations": [
|
|
||||||
{
|
|
||||||
"type": "node",
|
|
||||||
"request": "launch",
|
|
||||||
"name": "Jasmine Tests",
|
|
||||||
"program": "${workspaceFolder}/node_modules/jasmine/bin/jasmine.js",
|
|
||||||
"args": [
|
|
||||||
"${workspaceFolder}/test/encode_test.js"
|
|
||||||
],
|
|
||||||
"internalConsoleOptions": "openOnSessionStart"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
|
|
||||||
}
|
|
||||||
@ -1,26 +0,0 @@
|
|||||||
## Thanks
|
|
||||||
I would like to thank you for your valuable time and effort and applogies if this PR is rejected due to any reason.
|
|
||||||
|
|
||||||
Aim: Implementing Nimn specification so that Js object can be converted to nimn format.
|
|
||||||
|
|
||||||
### DoD
|
|
||||||
Here is the check list to publish any change
|
|
||||||
|
|
||||||
* Changes are not half implemented due to the library limitation or any other reason.
|
|
||||||
* Changes are well discussed by raising github issue. So they are well known by other contributers and users
|
|
||||||
* Echoing the above point. The purpose / goal for the PR should be mentioned in the description.
|
|
||||||
* Multiple unrelated changes should not be clubbed in single PR.
|
|
||||||
* If you are adding any dependency (specially if it is not the dev dependency) please check that
|
|
||||||
* it is not dependent on other language packages like c/c++
|
|
||||||
* the package is not very old or very new, discontinued, has any vulnerability etc.
|
|
||||||
* please check the performance and size of package
|
|
||||||
* please check alternate available options
|
|
||||||
* Please write tests for the new changes
|
|
||||||
* Don't forget to write tests for negative cases
|
|
||||||
* Don't comment existing test case.
|
|
||||||
|
|
||||||
Note that publishing changes or accepting any PR may take time. So please keep patience.
|
|
||||||
|
|
||||||
### Guidelines for first time contributors
|
|
||||||
|
|
||||||
* https://github.com/Roshanjossey/first-contributions
|
|
||||||
@ -1,21 +0,0 @@
|
|||||||
MIT License
|
|
||||||
|
|
||||||
Copyright (c) 2018 nimndata
|
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
||||||
of this software and associated documentation files (the "Software"), to deal
|
|
||||||
in the Software without restriction, including without limitation the rights
|
|
||||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
||||||
copies of the Software, and to permit persons to whom the Software is
|
|
||||||
furnished to do so, subject to the following conditions:
|
|
||||||
|
|
||||||
The above copyright notice and this permission notice shall be included in all
|
|
||||||
copies or substantial portions of the Software.
|
|
||||||
|
|
||||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
||||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
||||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
||||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
||||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
||||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
||||||
SOFTWARE.
|
|
||||||
@ -1,109 +0,0 @@
|
|||||||
# nimnjs-node
|
|
||||||
JS implementation of nimn specification. Highly Compressed JS object/JSON. 60% or more compressed than JSON, 40% or more compressed than msgpack
|
|
||||||
|
|
||||||
[](https://snyk.io/test/github/nimndata/nimnjs-node/)
|
|
||||||
[](https://travis-ci.org/nimndata/nimnjs-node/)
|
|
||||||
[](https://coveralls.io/github/nimndata/nimnjs-node/?branch=master)
|
|
||||||
[<img src="https://img.shields.io/badge/Try-me-blue.svg?colorA=FFA500&colorB=0000FF" alt="Try me"/>](https://nimndata.github.io/nimnjs-node/)
|
|
||||||
|
|
||||||
<a href="https://www.patreon.com/bePatron?u=9531404" data-patreon-widget-type="become-patron-button"><img src="https://c5.patreon.com/external/logo/become_a_patron_button.png" alt="Become a Patron!" width="200" /></a>
|
|
||||||
<a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=KQJAX48SPUKNC"> <img src="https://www.paypalobjects.com/webstatic/en_US/btn/btn_donate_92x26.png" alt="Stubmatic donate button"/></a>
|
|
||||||
|
|
||||||
<img align="right" src="static/img/nimnjs-logo.png" />
|
|
||||||
|
|
||||||
## Introduction
|
|
||||||
NIMN JS can parse JS object to nimn data and vice versa. See Nimn [specification](https://github.com/nimndata/spec) for more detail.
|
|
||||||
|
|
||||||
## Usages
|
|
||||||
First install or add to your npm package
|
|
||||||
```
|
|
||||||
$npm install nimnjs
|
|
||||||
```
|
|
||||||
|
|
||||||
```js
|
|
||||||
var nimn = require("nimnjs");
|
|
||||||
|
|
||||||
var schema = {
|
|
||||||
"name": "string",
|
|
||||||
"age": "number",
|
|
||||||
"human": "boolean",
|
|
||||||
"projects": [{
|
|
||||||
"name": "string",
|
|
||||||
"decription": "string"
|
|
||||||
}]
|
|
||||||
}
|
|
||||||
|
|
||||||
var nimnInstance = new nimn();
|
|
||||||
nimnInstance.addSchema(schema);
|
|
||||||
|
|
||||||
var data = {
|
|
||||||
"name" : "amit",
|
|
||||||
"age" : 32,
|
|
||||||
"human" : true,
|
|
||||||
"projects" : [
|
|
||||||
{
|
|
||||||
"name": "some",
|
|
||||||
"decription" : "some long description"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
|
|
||||||
var result = nimnInstance.encode(data);//Æamitº32ÙÇÆsomeºsome long description
|
|
||||||
result = nimnInstance.decode(result);
|
|
||||||
expect(result).toEqual(data);
|
|
||||||
```
|
|
||||||
|
|
||||||
For date compression
|
|
||||||
```js
|
|
||||||
var nimnDateparser = require("nimn-date-parser");
|
|
||||||
//generate schema and data
|
|
||||||
var nimnInstance = new nimn();
|
|
||||||
nimnInstance.addDataHandler("date",function(val){
|
|
||||||
return nimnDateparser.parse(val,true,true,true)
|
|
||||||
},function(val){
|
|
||||||
return nimnDateparser.parseBack(val,true,true,true)
|
|
||||||
});
|
|
||||||
nimnInstance.addSchema(schema); //add after adding all data handlers
|
|
||||||
|
|
||||||
var nimndata = nimnInstance.encode(data);
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
Encode enum type
|
|
||||||
```js
|
|
||||||
var nimnInstance = new nimn();
|
|
||||||
nimnInstance.addDataHandler("status",null,null,{
|
|
||||||
"M" : "Married",
|
|
||||||
"S" : "Single"
|
|
||||||
});
|
|
||||||
nimnInstance.addSchema(schema); //add after adding all data handlers
|
|
||||||
```
|
|
||||||
|
|
||||||
Just mark a data type
|
|
||||||
```js
|
|
||||||
var nimnInstance = new nimn();
|
|
||||||
nimnInstance.addDataHandler("image");
|
|
||||||
nimnInstance.addSchema(schema); //add after adding all data handlers
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
Include [dist](dist/nimn.js) in your HTML to use it in browser.
|
|
||||||
|
|
||||||
|
|
||||||
Check the [demo](https://nimndata.github.io/nimnjs-node/) for instant use. It generates schema automatically with the help of [schema builder](https://github.com/nimndata/nimnjs-schema-builder) when sample json is provided.
|
|
||||||
|
|
||||||
|
|
||||||
## Support
|
|
||||||
I need your expert advice, and contribution to grow nimn (निम्न) so that it can support all mazor languages. Please join the [official organization](https://github.com/nimndata) on github to support it. And ask your friends, and colleagues to give it a try. It can not only save bandwidth but speed up communication, search and much more.
|
|
||||||
|
|
||||||
|
|
||||||
### Worth to mention
|
|
||||||
|
|
||||||
- **[imglab](https://github.com/NaturalIntelligence/imglab)** : Web based tool to label images for object. So that they can be used to train dlib or other object detectors. You can integrate 3rd party libraries for fast labeling.
|
|
||||||
- **[अनुमार्गक (anumargak)](https://github.com/NaturalIntelligence/anumargak)** : The fastest router for node web servers.
|
|
||||||
|
|
||||||
- [Stubmatic](https://github.com/NaturalIntelligence/Stubmatic) : A stub server to mock behaviour of HTTP(s) / REST / SOAP services.
|
|
||||||
- **[fastify-xml-body-parser](https://github.com/NaturalIntelligence/fastify-xml-body-parser/)** : Fastify plugin / module to parse XML payload / body into JS object using fast-xml-parser.
|
|
||||||
- [fast-lorem-ipsum](https://github.com/amitguptagwl/fast-lorem-ipsum) : Generate lorem ipsum words, sentences, paragraph very quickly.
|
|
||||||
- [Grapes](https://github.com/amitguptagwl/grapes) : Flexible Regular expression engine which can be applied on char stream. (under development)
|
|
||||||
- [fast XML Parser](https://github.com/amitguptagwl/fast-xml-parser) : Fastest pure js XML parser for xml to js/json and vice versa. And XML validation.
|
|
||||||
@ -1,76 +0,0 @@
|
|||||||
{
|
|
||||||
"_args": [
|
|
||||||
[
|
|
||||||
"nimnjs@1.3.2",
|
|
||||||
"C:\\dev\\repos\\actions\\setup-dotnet"
|
|
||||||
]
|
|
||||||
],
|
|
||||||
"_from": "nimnjs@1.3.2",
|
|
||||||
"_id": "nimnjs@1.3.2",
|
|
||||||
"_inBundle": false,
|
|
||||||
"_integrity": "sha512-TIOtI4iqkQrUM1tiM76AtTQem0c7e56SkDZ7sj1d1MfUsqRcq2ZWQvej/O+HBTZV7u/VKnwlKTDugK/75IRPPw==",
|
|
||||||
"_location": "/nimnjs",
|
|
||||||
"_phantomChildren": {},
|
|
||||||
"_requested": {
|
|
||||||
"type": "version",
|
|
||||||
"registry": true,
|
|
||||||
"raw": "nimnjs@1.3.2",
|
|
||||||
"name": "nimnjs",
|
|
||||||
"escapedName": "nimnjs",
|
|
||||||
"rawSpec": "1.3.2",
|
|
||||||
"saveSpec": null,
|
|
||||||
"fetchSpec": "1.3.2"
|
|
||||||
},
|
|
||||||
"_requiredBy": [
|
|
||||||
"/fast-xml-parser"
|
|
||||||
],
|
|
||||||
"_resolved": "https://registry.npmjs.org/nimnjs/-/nimnjs-1.3.2.tgz",
|
|
||||||
"_spec": "1.3.2",
|
|
||||||
"_where": "C:\\dev\\repos\\actions\\setup-dotnet",
|
|
||||||
"author": {
|
|
||||||
"name": "Amit Gupta",
|
|
||||||
"url": "https://github.com/amitguptagwl"
|
|
||||||
},
|
|
||||||
"bugs": {
|
|
||||||
"url": "https://github.com/nimndata/nimnjs-node/issues"
|
|
||||||
},
|
|
||||||
"dependencies": {
|
|
||||||
"nimn-date-parser": "^1.0.0",
|
|
||||||
"nimn_schema_builder": "^1.0.0"
|
|
||||||
},
|
|
||||||
"description": "Schema aware compression of JS object/JSON data. 60% more compressed than json",
|
|
||||||
"devDependencies": {
|
|
||||||
"benchmark": "^2.1.4",
|
|
||||||
"browserify": "^15.1.0",
|
|
||||||
"cbor": "^4.0.0",
|
|
||||||
"istanbul": "^0.4.5",
|
|
||||||
"jasmine": "^3.0.0",
|
|
||||||
"jasmine-core": "^2.99.1",
|
|
||||||
"msgpack": "^1.0.2",
|
|
||||||
"notepack.io": "^2.1.2"
|
|
||||||
},
|
|
||||||
"homepage": "https://github.com/nimndata/nimnjs-node",
|
|
||||||
"keywords": [
|
|
||||||
"nimn",
|
|
||||||
"nimnjs",
|
|
||||||
"json",
|
|
||||||
"compress",
|
|
||||||
"parse",
|
|
||||||
"format",
|
|
||||||
"msgpack"
|
|
||||||
],
|
|
||||||
"license": "MIT",
|
|
||||||
"main": "src/nimn.js",
|
|
||||||
"name": "nimnjs",
|
|
||||||
"repository": {
|
|
||||||
"type": "git",
|
|
||||||
"url": "git+https://github.com/nimndata/nimnjs-node.git"
|
|
||||||
},
|
|
||||||
"scripts": {
|
|
||||||
"bundle": "browserify src/nimn.js -s nimn -o dist/nimn.js",
|
|
||||||
"coverage": "istanbul cover -x \"tests/*test.js\" jasmine tests/*test.js;",
|
|
||||||
"coverage:check": "istanbul check-coverage --branch 90 --statement 90",
|
|
||||||
"test": "jasmine tests/*test.js"
|
|
||||||
},
|
|
||||||
"version": "1.3.2"
|
|
||||||
}
|
|
||||||
@ -1,63 +0,0 @@
|
|||||||
/**
|
|
||||||
*
|
|
||||||
* @param {string} dataType
|
|
||||||
* @param {function} parse
|
|
||||||
* @param {function} parseBack
|
|
||||||
* @param {object} charset
|
|
||||||
* @param {boolean} treatAsUnique
|
|
||||||
*/
|
|
||||||
function DataHandler(dataType, /* parse, parseBack, */ charset,treatAsUnique){
|
|
||||||
this.dataType = dataType;
|
|
||||||
//parse || (this.parse = parse);
|
|
||||||
//parseBack || (this.parseBack = parseBack);
|
|
||||||
if(charset){
|
|
||||||
//this.hasFixedInstances = true;
|
|
||||||
this.char2val = charset;
|
|
||||||
this.val2char = {};
|
|
||||||
var keys = Object.keys(charset);
|
|
||||||
for(var i in keys){
|
|
||||||
var val = charset[keys[i]];
|
|
||||||
this.val2char[val] = keys[i];
|
|
||||||
}
|
|
||||||
|
|
||||||
this.charcodes = Object.keys(charset);
|
|
||||||
}
|
|
||||||
if(treatAsUnique){
|
|
||||||
this.hasFixedInstances = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
//this.treatAsUnique = treatAsUnique;
|
|
||||||
}
|
|
||||||
|
|
||||||
DataHandler.prototype.parse = function(a){
|
|
||||||
if(this.char2val){
|
|
||||||
return this.getCharCodeFor(a);
|
|
||||||
}else{
|
|
||||||
return a;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
DataHandler.prototype.parseBack = function(a){
|
|
||||||
if(this.char2val){
|
|
||||||
return this.getValueOf(a);
|
|
||||||
}else{
|
|
||||||
return a;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* returns an array of supported characters or empty array when it supportes dynamic data
|
|
||||||
*/
|
|
||||||
DataHandler.prototype.getCharCodes =function(){
|
|
||||||
return this.charcodes;
|
|
||||||
}
|
|
||||||
|
|
||||||
DataHandler.prototype.getValueOf =function(chCode){
|
|
||||||
return this.char2val[chCode];
|
|
||||||
}
|
|
||||||
|
|
||||||
DataHandler.prototype.getCharCodeFor =function(value){
|
|
||||||
return this.val2char[value];
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = DataHandler;
|
|
||||||
@ -1,40 +0,0 @@
|
|||||||
var char = require("./util").char;
|
|
||||||
|
|
||||||
|
|
||||||
/* 176-178
|
|
||||||
180-190
|
|
||||||
198-208
|
|
||||||
219-223
|
|
||||||
*/
|
|
||||||
|
|
||||||
const chars= {
|
|
||||||
nilChar : char(176),
|
|
||||||
missingChar : char(201),
|
|
||||||
nilPremitive : char(175),
|
|
||||||
missingPremitive : char(200),
|
|
||||||
|
|
||||||
emptyChar : char(178),
|
|
||||||
emptyValue: char(177),//empty Premitive
|
|
||||||
|
|
||||||
boundryChar : char(179),
|
|
||||||
|
|
||||||
objStart: char(198),
|
|
||||||
arrStart: char(204),
|
|
||||||
arrayEnd: char(185),
|
|
||||||
}
|
|
||||||
|
|
||||||
const charsArr = [
|
|
||||||
chars.nilChar ,
|
|
||||||
chars.nilPremitive,
|
|
||||||
chars.missingChar,
|
|
||||||
chars.missingPremitive,
|
|
||||||
chars.boundryChar ,
|
|
||||||
chars.emptyChar,
|
|
||||||
chars.emptyValue,
|
|
||||||
chars.arrayEnd,
|
|
||||||
chars.objStart,
|
|
||||||
chars.arrStart
|
|
||||||
]
|
|
||||||
|
|
||||||
exports.chars = chars;
|
|
||||||
exports.charsArr = charsArr;
|
|
||||||
@ -1,108 +0,0 @@
|
|||||||
var chars = require("./chars").chars;
|
|
||||||
|
|
||||||
decoder.prototype._d = function(schema){
|
|
||||||
if(ifNil(this.currentChar())){
|
|
||||||
this.index++;
|
|
||||||
return null;
|
|
||||||
}else if(ifMissing(this.currentChar())){
|
|
||||||
this.index++;
|
|
||||||
return undefined;
|
|
||||||
}else if(typeof schema.type === "string"){//premitive
|
|
||||||
return this.readPremitiveValue(schema);
|
|
||||||
}else if(Array.isArray(schema)){
|
|
||||||
if(this.currentChar() === chars.emptyChar){
|
|
||||||
this.index++;
|
|
||||||
return [];
|
|
||||||
}else if(this.currentChar() !== chars.arrStart){
|
|
||||||
throw Error("Parsing error: Array start char was expected");
|
|
||||||
}else{
|
|
||||||
this.index++;//skip array start char
|
|
||||||
var item = schema[0];
|
|
||||||
var obj = []
|
|
||||||
do{
|
|
||||||
var r = this._d(item) ;
|
|
||||||
if(r !== undefined){
|
|
||||||
obj.push(r);
|
|
||||||
}
|
|
||||||
}while(this.dataToDecode[this.index] !== chars.arrayEnd);
|
|
||||||
++this.index;
|
|
||||||
return obj;
|
|
||||||
}
|
|
||||||
}else{//object
|
|
||||||
if(this.currentChar() === chars.emptyChar){
|
|
||||||
this.index++;
|
|
||||||
return {};
|
|
||||||
}else if(this.currentChar() !== chars.objStart){
|
|
||||||
throw Error("Parsing error: Object start char was expected : " + this.currentChar());
|
|
||||||
}else{
|
|
||||||
this.index++;//skip object start char
|
|
||||||
var keys = Object.keys(schema);
|
|
||||||
var len = keys.length;
|
|
||||||
var obj = {};
|
|
||||||
for(var i=0; i< len; i++){
|
|
||||||
|
|
||||||
var r = this._d(schema[keys[i]]) ;
|
|
||||||
if(r !== undefined){
|
|
||||||
obj[keys[i]] = r;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return obj;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function ifNil(ch){
|
|
||||||
return ch === chars.nilChar || ch === chars.nilPremitive;
|
|
||||||
}
|
|
||||||
|
|
||||||
function ifMissing(ch){
|
|
||||||
return ch === chars.missingChar || ch === chars.missingPremitive;
|
|
||||||
}
|
|
||||||
/**
|
|
||||||
* returns character index pointing to
|
|
||||||
*/
|
|
||||||
decoder.prototype.currentChar = function(){
|
|
||||||
return this.dataToDecode[this.index];
|
|
||||||
}
|
|
||||||
|
|
||||||
decoder.prototype.readPremitiveValue = function(schemaOfCurrentKey){
|
|
||||||
var val = this.readFieldValue(schemaOfCurrentKey);
|
|
||||||
if(this.currentChar() === chars.boundryChar) this.index++;
|
|
||||||
var dh = this.dataHandlers[schemaOfCurrentKey.type];
|
|
||||||
return dh.parseBack(val);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Read characters until app supported char is found
|
|
||||||
*/
|
|
||||||
decoder.prototype.readFieldValue = function(schemaOfCurrentKey){
|
|
||||||
if(schemaOfCurrentKey.readUntil){
|
|
||||||
if(this.currentChar() === chars.emptyValue){
|
|
||||||
this.index++;
|
|
||||||
return "";
|
|
||||||
}else{
|
|
||||||
var until = schemaOfCurrentKey.readUntil;
|
|
||||||
var len = this.dataToDecode.length;
|
|
||||||
var start = this.index;
|
|
||||||
|
|
||||||
for(;this.index < len && until.indexOf(this.currentChar()) === -1;this.index++);
|
|
||||||
return this.dataToDecode.substr(start, this.index-start);
|
|
||||||
}
|
|
||||||
}else{
|
|
||||||
return this.dataToDecode[this.index++];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
decoder.prototype.decode = function(objStr){
|
|
||||||
this.index= 0;
|
|
||||||
if(!objStr || typeof objStr !== "string" || objStr.length === 0) throw Error("input should be a valid string");
|
|
||||||
this.dataToDecode = objStr;
|
|
||||||
return this._d(this.schema);
|
|
||||||
}
|
|
||||||
|
|
||||||
function decoder(schema,dataHandlers){
|
|
||||||
this.schema = schema;
|
|
||||||
this.dataHandlers = dataHandlers;
|
|
||||||
}
|
|
||||||
module.exports = decoder;
|
|
||||||
@ -1,89 +0,0 @@
|
|||||||
var chars = require("./chars").chars;
|
|
||||||
var appCharsArr = require("./chars").charsArr;
|
|
||||||
|
|
||||||
Encoder.prototype._e = function(jObj,e_schema){
|
|
||||||
if(typeof e_schema.type === "string"){//premitive
|
|
||||||
return this.getValue(jObj,e_schema.type);
|
|
||||||
}else{
|
|
||||||
var hasValidData = hasData(jObj);
|
|
||||||
if(hasValidData === true){
|
|
||||||
var str = "";
|
|
||||||
if(Array.isArray(e_schema)){
|
|
||||||
str += chars.arrStart;
|
|
||||||
var itemSchema = e_schema[0];
|
|
||||||
//var itemSchemaType = itemSchema;
|
|
||||||
var arr_len = jObj.length;
|
|
||||||
for(var arr_i=0;arr_i < arr_len;arr_i++){
|
|
||||||
var r = this._e(jObj[arr_i],itemSchema) ;
|
|
||||||
str = this.processValue(str,r);
|
|
||||||
}
|
|
||||||
str += chars.arrayEnd;//indicates that next item is not array item
|
|
||||||
}else{//object
|
|
||||||
str += chars.objStart;
|
|
||||||
var keys = Object.keys(e_schema);
|
|
||||||
for(var i in keys){
|
|
||||||
var key = keys[i];
|
|
||||||
var r = this._e(jObj[key],e_schema[key]) ;
|
|
||||||
str = this.processValue(str,r);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return str;
|
|
||||||
}else{
|
|
||||||
return hasValidData;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Encoder.prototype.processValue= function(str,r){
|
|
||||||
if(!this.isAppChar(r[0]) && !this.isAppChar(str[str.length -1])){
|
|
||||||
str += chars.boundryChar;
|
|
||||||
}
|
|
||||||
return str + r;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
*
|
|
||||||
* @param {*} a
|
|
||||||
* @param {*} type
|
|
||||||
* @return {string} return either the parsed value or a special char representing the value
|
|
||||||
*/
|
|
||||||
Encoder.prototype.getValue= function(a,type){
|
|
||||||
switch(a){
|
|
||||||
case undefined: return chars.missingPremitive;
|
|
||||||
case null: return chars.nilPremitive;
|
|
||||||
case "": return chars.emptyValue;
|
|
||||||
default: return this.dataHandlers[type].parse(a);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Check if the given object is empty, null, or undefined. Returns true otherwise.
|
|
||||||
* @param {*} jObj
|
|
||||||
*/
|
|
||||||
function hasData(jObj){
|
|
||||||
if(jObj === undefined) return chars.missingChar;
|
|
||||||
else if(jObj === null) return chars.nilChar;
|
|
||||||
else if( jObj.length === 0 || Object.keys(jObj).length === 0){
|
|
||||||
return chars.emptyChar;
|
|
||||||
}else{
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Encoder.prototype.isAppChar = function(ch){
|
|
||||||
return this.handledChars.indexOf(ch) !== -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
Encoder.prototype.encode = function(jObj){
|
|
||||||
return this._e(jObj,this.schema);
|
|
||||||
}
|
|
||||||
|
|
||||||
function Encoder(schema,dHandlers, charArr){
|
|
||||||
this.dataHandlers = dHandlers;
|
|
||||||
this.handledChars = appCharsArr.slice();
|
|
||||||
this.handledChars = this.handledChars.concat(charArr);
|
|
||||||
|
|
||||||
this.schema = schema;
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = Encoder;
|
|
||||||
@ -1,27 +0,0 @@
|
|||||||
|
|
||||||
/**
|
|
||||||
* Verify if all the datahandlers are added given in schema.
|
|
||||||
* @param {*} schema
|
|
||||||
* @param {*} datahandlers
|
|
||||||
*/
|
|
||||||
var validateSchema = function(schema,datahandlers){
|
|
||||||
if(Array.isArray(schema)){
|
|
||||||
validateSchema(schema[0],datahandlers);
|
|
||||||
}else if(typeof schema === "object"){
|
|
||||||
var keys = Object.keys(schema);
|
|
||||||
var len = keys.length;
|
|
||||||
|
|
||||||
for(var i=0; i< len; i++){
|
|
||||||
var key = keys[i];
|
|
||||||
var nextKey = keys[i+1];
|
|
||||||
|
|
||||||
validateSchema(schema[key],datahandlers);
|
|
||||||
}
|
|
||||||
}else{
|
|
||||||
if(!datahandlers[schema]){
|
|
||||||
throw Error("You've forgot to add data handler for " + schema)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
exports.validateSchema = validateSchema;
|
|
||||||
@ -1,95 +0,0 @@
|
|||||||
var boolean = require("./parsers/boolean");
|
|
||||||
var numParser = require("./parsers/number");
|
|
||||||
var chars = require("./chars").chars;
|
|
||||||
var appCharsArr = require("./chars").charsArr;
|
|
||||||
var helper = require("./helper");
|
|
||||||
var schemaMarker = require("./schemaMarker");
|
|
||||||
var Decoder = require("./decoder");
|
|
||||||
var Encoder = require("./encoder");
|
|
||||||
var DataHandler = require("./DataHandler");
|
|
||||||
|
|
||||||
function nimn() {
|
|
||||||
this.handledChars = [];//appCharsArr.slice();
|
|
||||||
this.dataHandlers = {};
|
|
||||||
this.addDataHandler("boolean",null,null,boolean.charset,true);
|
|
||||||
//this.addDataHandler("boolean",boolean.parse,boolean.parseBack,boolean.charset,true);
|
|
||||||
this.addDataHandler("string");
|
|
||||||
this.addDataHandler("number",numParser.parse, numParser.parseBack);
|
|
||||||
this.addDataHandler("date");
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* This method should be called once all the data handlers are registered.
|
|
||||||
* It updates internal schema based on given schema.
|
|
||||||
*
|
|
||||||
* @example
|
|
||||||
* {
|
|
||||||
* "field1" : "string",
|
|
||||||
* "field2" : "date",
|
|
||||||
* "field3" : {
|
|
||||||
* "field4" : "number"
|
|
||||||
* },
|
|
||||||
* "field5" : [ "image"],
|
|
||||||
* "field6" : [{ "field7" : "boolean"}]
|
|
||||||
* }
|
|
||||||
* @param {*} schema
|
|
||||||
* @returns {void}
|
|
||||||
*/
|
|
||||||
nimn.prototype.addSchema= function(schema){
|
|
||||||
this.schema = JSON.parse(JSON.stringify(schema));
|
|
||||||
new schemaMarker(this.dataHandlers).markNextPossibleChars(this.schema);
|
|
||||||
//helper.validateSchema(schema,this.dataHandlers);
|
|
||||||
this.encoder = new Encoder(this.schema,this.dataHandlers,this.handledChars);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* You can update existnig handler od add new using this method.
|
|
||||||
* "string", "number", "boolean", and "date" are handled by default.
|
|
||||||
*
|
|
||||||
* charset should be set when given type should be treated as enum or fixed set of values
|
|
||||||
* @example
|
|
||||||
* //to map
|
|
||||||
* nimnInstance.addDataHandler("status",null,null,{ "R": "running", "S" : "stop", "I", "ready to run"},false)
|
|
||||||
* @example
|
|
||||||
* //just for identification
|
|
||||||
* nimnInstance.addDataHandler("image");
|
|
||||||
* @example
|
|
||||||
* //to compress more
|
|
||||||
* nimnInstance.addDataHandler("date", datecompressor.parse, datecompressor.parseBack);
|
|
||||||
* @param {string} type
|
|
||||||
* @param {function} parseWith - will be used by encoder to encode given type's value
|
|
||||||
* @param {function} parseBackWith - will be used by decoder to decode given type's value
|
|
||||||
* @param {Object} charset - map of charset and fixed values
|
|
||||||
* @param {boolean} [noBoundaryChar=false] - if true encoder will not separate given type's value with boundary char
|
|
||||||
*/
|
|
||||||
nimn.prototype.addDataHandler = function(type,parseWith,parseBackWith,charset,noBoundaryChar){
|
|
||||||
var dataHandler = new DataHandler(type,/* parseWith,parseBackWith, */charset,noBoundaryChar);
|
|
||||||
if(parseWith) dataHandler.parse = parseWith;
|
|
||||||
if(parseBackWith) dataHandler.parseBack = parseBackWith;
|
|
||||||
|
|
||||||
//unque charset don't require boundary char. Hence check them is they are already added
|
|
||||||
if(noBoundaryChar && charset){
|
|
||||||
var keys = Object.keys(charset);
|
|
||||||
|
|
||||||
for(var k in keys){
|
|
||||||
var ch = keys[k];
|
|
||||||
if(this.handledChars.indexOf(ch) !== -1 || appCharsArr.indexOf(ch) !== -1){
|
|
||||||
throw Error("DataHandler Error: "+ ch +" is not allowed. Either it is reserved or being used by another data handler");
|
|
||||||
}else{
|
|
||||||
this.handledChars.push(ch);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
this.dataHandlers[type] = dataHandler;
|
|
||||||
}
|
|
||||||
|
|
||||||
nimn.prototype.encode = function(jObj){
|
|
||||||
return this.encoder.encode(jObj);
|
|
||||||
}
|
|
||||||
|
|
||||||
nimn.prototype.decode= function(encodedVal){
|
|
||||||
var decoder = new Decoder(this.schema,this.dataHandlers);
|
|
||||||
return decoder.decode(encodedVal);
|
|
||||||
}
|
|
||||||
module.exports = nimn;
|
|
||||||
@ -1,11 +0,0 @@
|
|||||||
var chars = require("../chars").chars;
|
|
||||||
var char = require("../util").char;
|
|
||||||
|
|
||||||
var yes = char(181);
|
|
||||||
var no = char(183);
|
|
||||||
|
|
||||||
booleanCharset = {};
|
|
||||||
booleanCharset[yes] = true;
|
|
||||||
booleanCharset[no] = false;
|
|
||||||
|
|
||||||
exports.charset = booleanCharset;
|
|
||||||
@ -1,18 +0,0 @@
|
|||||||
var chars = require("../chars").chars;
|
|
||||||
|
|
||||||
function parse(val){
|
|
||||||
return val;
|
|
||||||
}
|
|
||||||
|
|
||||||
function parseBack(val){
|
|
||||||
if(val.indexOf(".") !== -1){
|
|
||||||
val = Number.parseFloat(val);
|
|
||||||
}else{
|
|
||||||
val = Number.parseInt(val,10);
|
|
||||||
}
|
|
||||||
return val;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
exports.parse = parse;
|
|
||||||
exports.parseBack = parseBack;
|
|
||||||
@ -1,125 +0,0 @@
|
|||||||
var chars = require("./chars").chars;
|
|
||||||
var appCharsArr = require("./chars").charsArr;
|
|
||||||
|
|
||||||
schemaMarker.prototype._m = function(schema){
|
|
||||||
if(Array.isArray(schema)){
|
|
||||||
if(typeof schema[0] === "string"){
|
|
||||||
var itemSchema = {
|
|
||||||
type : schema[0]
|
|
||||||
}
|
|
||||||
this.setReadUntil(itemSchema, schema[0]);
|
|
||||||
schema[0] = itemSchema;//make it object so a function cant set it's value
|
|
||||||
if(schema[0].readUntil)
|
|
||||||
schema[0].readUntil.push(chars.arrayEnd);
|
|
||||||
}else{
|
|
||||||
this._m(schema[0]);//let's object portion handle it
|
|
||||||
var lastMostKey = getLastMostKey(schema[0]);
|
|
||||||
if(lastMostKey){
|
|
||||||
this.setReadUntil(lastMostKey, schema[0]);
|
|
||||||
if(lastMostKey.readUntil)
|
|
||||||
lastMostKey.readUntil.push(chars.arrayEnd);
|
|
||||||
}else{
|
|
||||||
//lastmostkey was set as it was under an array
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}else if(typeof schema === "object"){
|
|
||||||
var keys = Object.keys(schema);
|
|
||||||
var len = keys.length;
|
|
||||||
|
|
||||||
for(var i=0; i< len; i++){
|
|
||||||
var key = keys[i];
|
|
||||||
var nextKey = keys[i+1];
|
|
||||||
|
|
||||||
this._m(schema[key]);
|
|
||||||
if(Array.isArray(schema[key])) continue;
|
|
||||||
else if(nextKey){
|
|
||||||
if(typeof schema[key] !== "string"){//not an object
|
|
||||||
var lastMostKey = getLastMostKey(schema[key]);
|
|
||||||
if(lastMostKey){
|
|
||||||
this.setReadUntil(lastMostKey,schema[nextKey]);
|
|
||||||
}else{
|
|
||||||
//lastmostkey was set as it was under an array
|
|
||||||
}
|
|
||||||
}else{
|
|
||||||
var itemSchema = {
|
|
||||||
type : schema[key]
|
|
||||||
}
|
|
||||||
this.setReadUntil(itemSchema,schema[nextKey]);
|
|
||||||
schema[key] = itemSchema ;
|
|
||||||
}
|
|
||||||
}else{
|
|
||||||
if(typeof schema[key] === "object") continue;
|
|
||||||
schema[key] = {
|
|
||||||
type : schema[key]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}else{
|
|
||||||
if(!this.dataHandlers[schema]){//handled
|
|
||||||
throw Error("You've forgot to add data handler for " + schema)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
schemaMarker.prototype.setReadUntil = function(current,next){
|
|
||||||
//status: R,S
|
|
||||||
if(this.dataHandlers[current.type].hasFixedInstances){
|
|
||||||
//if current char is set by user and need to be separated by boundary char
|
|
||||||
//then don't set readUntil, read current char
|
|
||||||
return ;
|
|
||||||
}else{
|
|
||||||
|
|
||||||
//return [chars.boundryChar, chars.missingPremitive, chars.nilPremitive];
|
|
||||||
if(Array.isArray(next)){
|
|
||||||
current.readUntil = [ chars.arrStart, chars.missingChar, chars.emptyChar, chars.nilChar];
|
|
||||||
}else if(typeof next === "object"){
|
|
||||||
current.readUntil = [ chars.objStart, chars.missingChar, chars.emptyChar, chars.nilChar];
|
|
||||||
}else{
|
|
||||||
if(this.dataHandlers[next] && this.dataHandlers[next].hasFixedInstances){//but need to be separated by boundary char
|
|
||||||
//status,boolean
|
|
||||||
current.readUntil = [chars.missingPremitive, chars.nilPremitive];
|
|
||||||
current.readUntil = current.readUntil.concat(this.dataHandlers[next].getCharCodes());
|
|
||||||
}else{
|
|
||||||
///status,age
|
|
||||||
current.readUntil = [chars.boundryChar, chars.emptyValue, chars.missingPremitive, chars.nilPremitive];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* obj can't be an array
|
|
||||||
* @param {*} obj
|
|
||||||
*/
|
|
||||||
function getLastMostKey(obj){
|
|
||||||
var lastProperty;
|
|
||||||
if(Array.isArray(obj)){
|
|
||||||
return;
|
|
||||||
}else{
|
|
||||||
var keys = Object.keys(obj);
|
|
||||||
lastProperty = obj[keys[keys.length-1]];
|
|
||||||
}
|
|
||||||
|
|
||||||
if(typeof lastProperty === "object" && !(lastProperty.type && typeof lastProperty.type === "string")){
|
|
||||||
return getLastMostKey(lastProperty);
|
|
||||||
}else{
|
|
||||||
return lastProperty;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
schemaMarker.prototype.markNextPossibleChars = function(schema){
|
|
||||||
this._m(schema);
|
|
||||||
if(!Array.isArray(schema)){
|
|
||||||
var lastMostKey = getLastMostKey(schema);
|
|
||||||
if(lastMostKey){
|
|
||||||
lastMostKey.readUntil = [chars.nilChar]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
function schemaMarker(dataHandlers){
|
|
||||||
this.dataHandlers = dataHandlers;
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = schemaMarker;
|
|
||||||
@ -1,30 +0,0 @@
|
|||||||
/**
|
|
||||||
* converts a ASCII number into equivalant ASCII char
|
|
||||||
* @param {number} a
|
|
||||||
* @returns ASCII char
|
|
||||||
*/
|
|
||||||
var char = function (a){
|
|
||||||
return String.fromCharCode(a);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* return key of an object
|
|
||||||
* @param {*} obj
|
|
||||||
* @param {number} i
|
|
||||||
*/
|
|
||||||
/* function getKey(obj,i){
|
|
||||||
return obj[Object.keys(obj)[i]];
|
|
||||||
}
|
|
||||||
*/
|
|
||||||
|
|
||||||
/* function indexOf(arr,searchedID) {
|
|
||||||
var arrayLen = arr.length;
|
|
||||||
var c = 0;
|
|
||||||
while (c < arrayLen) {
|
|
||||||
if (arr[c] === searchedID) return c;
|
|
||||||
c++;
|
|
||||||
}
|
|
||||||
return -1;
|
|
||||||
} */
|
|
||||||
exports.char = char;
|
|
||||||
//exports.indexOf = indexOf;
|
|
||||||
Loading…
Reference in New Issue