mirror of
https://github.com/kennethreitz/bake.git
synced 2026-06-05 23:00:17 +00:00
cleanup
This commit is contained in:
+21
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2016 Kevin Gravier
|
||||
|
||||
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.
|
||||
+171
@@ -0,0 +1,171 @@
|
||||
# External Editor
|
||||
|
||||
[](https://travis-ci.org/mrkmg/node-external-editor/branches)
|
||||
[](https://www.npmjs.com/package/external-editor)
|
||||
[](https://opensource.org/licenses/MIT)
|
||||
|
||||
|
||||
A node module to edit a string with a users preferred text editor using $VISUAL or $ENVIRONMENT.
|
||||
|
||||
Version: 3.1.0
|
||||
|
||||
As of version 3.0.0, the minimum version of node supported is 4.
|
||||
|
||||
## Install
|
||||
|
||||
`npm install external-editor --save`
|
||||
|
||||
## Usage
|
||||
|
||||
A simple example using the `.edit` convenience method
|
||||
|
||||
import {edit} from "external-editor";
|
||||
const data = edit('\n\n# Please write your text above');
|
||||
console.log(data);
|
||||
|
||||
A full featured example
|
||||
|
||||
import {ExternalEditor, CreateFileError, ReadFileError, RemoveFileError} from "external-editor"
|
||||
|
||||
try {
|
||||
const editor = new ExternalEditor();
|
||||
const text = editor.run() // the text is also available in editor.text
|
||||
|
||||
if (editor.last_exit_status !== 0) {
|
||||
console.log("The editor exited with a non-zero code");
|
||||
}
|
||||
} catch (err) {
|
||||
if (err instanceOf CreateFileError) {
|
||||
console.log('Failed to create the temporary file');
|
||||
} else if (err instanceOf ReadFileError) {
|
||||
console.log('Failed to read the temporary file');
|
||||
} else if (err instanceOf LaunchEditorError) {
|
||||
console.log('Failed to launch your editor');
|
||||
} else {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
// Do things with the text
|
||||
|
||||
// Eventually call the cleanup to remove the temporary file
|
||||
try {
|
||||
editor.cleanup();
|
||||
} catch (err) {
|
||||
if (err instanceOf RemoveFileError) {
|
||||
console.log('Failed to remove the temporary file');
|
||||
} else {
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#### API
|
||||
**Convenience Methods**
|
||||
|
||||
- `edit(text, config)`
|
||||
- `text` (string) *Optional* Defaults to empty string
|
||||
- `config` (Config) *Optional* Options for temporary file creation
|
||||
- **Returns** (string) The contents of the file
|
||||
- Could throw `CreateFileError`, `ReadFileError`, or `LaunchEditorError`, or `RemoveFileError`
|
||||
- `editAsync(text, callback, config)`
|
||||
- `text` (string) *Optional* Defaults to empty string
|
||||
- `callback` (function (error, text))
|
||||
- `error` could be of type `CreateFileError`, `ReadFileError`, or `LaunchEditorError`, or `RemoveFileError`
|
||||
- `text`(string) The contents of the file
|
||||
- `config` (Config) *Optional* Options for temporary file creation
|
||||
|
||||
|
||||
**Errors**
|
||||
|
||||
- `CreateFileError` Error thrown if the temporary file could not be created.
|
||||
- `ReadFileError` Error thrown if the temporary file could not be read.
|
||||
- `RemoveFileError` Error thrown if the temporary file could not be removed during cleanup.
|
||||
- `LaunchEditorError` Error thrown if the editor could not be launched.
|
||||
|
||||
**External Editor Public Methods**
|
||||
|
||||
- `new ExternalEditor(text, config)`
|
||||
- `text` (string) *Optional* Defaults to empty string
|
||||
- `config` (Config) *Optional* Options for temporary file creation
|
||||
- Could throw `CreateFileError`
|
||||
- `run()` Launches the editor.
|
||||
- **Returns** (string) The contents of the file
|
||||
- Could throw `LaunchEditorError` or `ReadFileError`
|
||||
- `runAsync(callback)` Launches the editor in an async way
|
||||
- `callback` (function (error, text))
|
||||
- `error` could be of type `ReadFileError` or `LaunchEditorError`
|
||||
- `text`(string) The contents of the file
|
||||
- `cleanup()` Removes the temporary file.
|
||||
- Could throw `RemoveFileError`
|
||||
|
||||
**External Editor Public Properties**
|
||||
|
||||
- `text` (string) *readonly* The text in the temporary file.
|
||||
- `editor.bin` (string) The editor determined from the environment.
|
||||
- `editor.args` (array) Default arguments for the bin
|
||||
- `tempFile` (string) Path to temporary file. Can be changed, but be careful as the temporary file probably already
|
||||
exists and would need be removed manually.
|
||||
- `lastExitStatus` (number) The last exit code emitted from the editor.
|
||||
|
||||
**Config Options**
|
||||
|
||||
- `prefix` (string) *Optional* A prefix for the file name.
|
||||
- `postfix` (string; *Optional* A postfix for the file name. Useful if you want to provide an extension.
|
||||
- `mode` (number) *Optional* Which mode to create the file with. e.g. 644
|
||||
- `template` (string) *Optional* A template for the filename. See [tmp](https://www.npmjs.com/package/tmp).
|
||||
- `dir` (string) *Optional* Which path to store the file.
|
||||
|
||||
## Errors
|
||||
|
||||
All errors have a simple message explaining what went wrong. They all also have an `originalError` property containing
|
||||
the original error thrown for debugging purposes.
|
||||
|
||||
## Why Synchronous?
|
||||
|
||||
Everything is synchronous to make sure the editor has complete control of the stdin and stdout. Testing has shown
|
||||
async launching of the editor can lead to issues when using readline or other packages which try to read from stdin or
|
||||
write to stdout. Seeing as this will be used in an interactive CLI environment, I made the decision to force the package
|
||||
to be synchronous. If you know a reliable way to force all stdin and stdout to be limited only to the child_process,
|
||||
please submit a PR.
|
||||
|
||||
If async is really needed, you can use `editAsync` or `runAsync`. If you are using readline or have anything else
|
||||
listening to the stdin or you write to stdout, you will most likely have problem, so make sure to remove any other
|
||||
listeners on stdin, stdout, or stderr.
|
||||
|
||||
## Demo
|
||||
|
||||
[](https://asciinema.org/a/a1qh9lypbe65mj0ivfuoslz2s)
|
||||
|
||||
## Breaking Changes from v2 to v3
|
||||
|
||||
- NodeJS 0.12 support dropped.
|
||||
- Switched to named imports.
|
||||
- All "snake_cased" variables and properties are now "camelCased".
|
||||
- `ExternalEditor.temp_file` is now `ExternalEditor.tempFile`.
|
||||
- `ExternalEditor.last_exit_status` is now `ExternalEditor.lastExitStatus`.
|
||||
- `Error.original_error` is now `Error.originalError`.
|
||||
|
||||
## License
|
||||
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2016-2018 Kevin Gravier
|
||||
|
||||
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.
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
var ExternalEditor = require('./main').ExternalEditor;
|
||||
var readline = require('readline');
|
||||
|
||||
var rl = readline.createInterface({
|
||||
input: process.stdin,
|
||||
output: null
|
||||
});
|
||||
|
||||
var message = '\n\n# Please Write a message\n# Any line starting with # is ignored';
|
||||
|
||||
process.stdout.write('Please write a message. (press enter to launch your preferred editor)');
|
||||
|
||||
editor = new ExternalEditor(message);
|
||||
|
||||
rl.on('line', function () {
|
||||
try {
|
||||
rl.pause();
|
||||
editor.runAsync(function (error, response)
|
||||
{
|
||||
if (error) {
|
||||
process.stdout.write(error.message);
|
||||
process.exit(1);
|
||||
}
|
||||
if (response.length === 0) {
|
||||
readline.moveCursor(process.stdout, 0, -1);
|
||||
process.stdout.write('Your message was empty, please try again. (press enter to launch your preferred editor)');
|
||||
rl.resume();
|
||||
} else {
|
||||
process.stdout.write('Your Message:\n');
|
||||
process.stdout.write(response);
|
||||
process.stdout.write('\n');
|
||||
rl.close();
|
||||
}
|
||||
});
|
||||
} catch (err) {
|
||||
process.stderr.write(err.message);
|
||||
process.stdout.write('\n');
|
||||
rl.close();
|
||||
}
|
||||
});
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
var ExternalEditor = require('./main').ExternalEditor;
|
||||
var readline = require('readline');
|
||||
|
||||
var rl = readline.createInterface({
|
||||
input: process.stdin,
|
||||
output: null
|
||||
});
|
||||
|
||||
var message = '\n\n# Please Write a message\n# Any line starting with # is ignored';
|
||||
|
||||
process.stdout.write('Please write a message. (press enter to launch your preferred editor)');
|
||||
|
||||
editor = new ExternalEditor(message);
|
||||
|
||||
rl.on('line', function () {
|
||||
try {
|
||||
// Get response, remove all lines starting with #, remove any trailing newlines.
|
||||
var response = editor.run().replace(/^#.*\n?/gm, '').replace(/\n+$/g, '').trim();
|
||||
|
||||
if (editor.lastExitStatus !== 0) {
|
||||
process.stderr.write("WARN: The editor exited with a non-zero status\n\n")
|
||||
}
|
||||
|
||||
if (response.length === 0) {
|
||||
readline.moveCursor(process.stdout, 0, -1);
|
||||
process.stdout.write('Your message was empty, please try again. (press enter to launch your preferred editor)');
|
||||
} else {
|
||||
process.stdout.write('Your Message:\n');
|
||||
process.stdout.write(response);
|
||||
process.stdout.write('\n');
|
||||
rl.close();
|
||||
}
|
||||
} catch (err) {
|
||||
process.stderr.write(err.message);
|
||||
process.stdout.write('\n');
|
||||
rl.close();
|
||||
}
|
||||
});
|
||||
Generated
Vendored
+10
@@ -0,0 +1,10 @@
|
||||
/***
|
||||
* Node External Editor
|
||||
*
|
||||
* Kevin Gravier <kevin@mrkmg.com>
|
||||
* MIT 2018
|
||||
*/
|
||||
export declare class CreateFileError extends Error {
|
||||
originalError: Error;
|
||||
constructor(originalError: Error);
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
"use strict";
|
||||
/***
|
||||
* Node External Editor
|
||||
*
|
||||
* Kevin Gravier <kevin@mrkmg.com>
|
||||
* MIT 2018
|
||||
*/
|
||||
var __extends = (this && this.__extends) || (function () {
|
||||
var extendStatics = function (d, b) {
|
||||
extendStatics = Object.setPrototypeOf ||
|
||||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
|
||||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
|
||||
return extendStatics(d, b);
|
||||
};
|
||||
return function (d, b) {
|
||||
extendStatics(d, b);
|
||||
function __() { this.constructor = d; }
|
||||
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
|
||||
};
|
||||
})();
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
var CreateFileError = /** @class */ (function (_super) {
|
||||
__extends(CreateFileError, _super);
|
||||
function CreateFileError(originalError) {
|
||||
var _newTarget = this.constructor;
|
||||
var _this = _super.call(this, "Failed to create temporary file for editor") || this;
|
||||
_this.originalError = originalError;
|
||||
var proto = _newTarget.prototype;
|
||||
if (Object.setPrototypeOf) {
|
||||
Object.setPrototypeOf(_this, proto);
|
||||
}
|
||||
else {
|
||||
_this.__proto__ = _newTarget.prototype;
|
||||
}
|
||||
return _this;
|
||||
}
|
||||
return CreateFileError;
|
||||
}(Error));
|
||||
exports.CreateFileError = CreateFileError;
|
||||
Generated
Vendored
+10
@@ -0,0 +1,10 @@
|
||||
/***
|
||||
* Node External Editor
|
||||
*
|
||||
* Kevin Gravier <kevin@mrkmg.com>
|
||||
* MIT 2018
|
||||
*/
|
||||
export declare class LaunchEditorError extends Error {
|
||||
originalError: Error;
|
||||
constructor(originalError: Error);
|
||||
}
|
||||
Generated
Vendored
+39
@@ -0,0 +1,39 @@
|
||||
"use strict";
|
||||
/***
|
||||
* Node External Editor
|
||||
*
|
||||
* Kevin Gravier <kevin@mrkmg.com>
|
||||
* MIT 2018
|
||||
*/
|
||||
var __extends = (this && this.__extends) || (function () {
|
||||
var extendStatics = function (d, b) {
|
||||
extendStatics = Object.setPrototypeOf ||
|
||||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
|
||||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
|
||||
return extendStatics(d, b);
|
||||
};
|
||||
return function (d, b) {
|
||||
extendStatics(d, b);
|
||||
function __() { this.constructor = d; }
|
||||
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
|
||||
};
|
||||
})();
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
var LaunchEditorError = /** @class */ (function (_super) {
|
||||
__extends(LaunchEditorError, _super);
|
||||
function LaunchEditorError(originalError) {
|
||||
var _newTarget = this.constructor;
|
||||
var _this = _super.call(this, "Failed launch editor") || this;
|
||||
_this.originalError = originalError;
|
||||
var proto = _newTarget.prototype;
|
||||
if (Object.setPrototypeOf) {
|
||||
Object.setPrototypeOf(_this, proto);
|
||||
}
|
||||
else {
|
||||
_this.__proto__ = _newTarget.prototype;
|
||||
}
|
||||
return _this;
|
||||
}
|
||||
return LaunchEditorError;
|
||||
}(Error));
|
||||
exports.LaunchEditorError = LaunchEditorError;
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
/***
|
||||
* Node External Editor
|
||||
*
|
||||
* Kevin Gravier <kevin@mrkmg.com>
|
||||
* MIT 2018
|
||||
*/
|
||||
export declare class ReadFileError extends Error {
|
||||
originalError: Error;
|
||||
constructor(originalError: Error);
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
"use strict";
|
||||
/***
|
||||
* Node External Editor
|
||||
*
|
||||
* Kevin Gravier <kevin@mrkmg.com>
|
||||
* MIT 2018
|
||||
*/
|
||||
var __extends = (this && this.__extends) || (function () {
|
||||
var extendStatics = function (d, b) {
|
||||
extendStatics = Object.setPrototypeOf ||
|
||||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
|
||||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
|
||||
return extendStatics(d, b);
|
||||
};
|
||||
return function (d, b) {
|
||||
extendStatics(d, b);
|
||||
function __() { this.constructor = d; }
|
||||
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
|
||||
};
|
||||
})();
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
var ReadFileError = /** @class */ (function (_super) {
|
||||
__extends(ReadFileError, _super);
|
||||
function ReadFileError(originalError) {
|
||||
var _newTarget = this.constructor;
|
||||
var _this = _super.call(this, "Failed to read temporary file") || this;
|
||||
_this.originalError = originalError;
|
||||
var proto = _newTarget.prototype;
|
||||
if (Object.setPrototypeOf) {
|
||||
Object.setPrototypeOf(_this, proto);
|
||||
}
|
||||
else {
|
||||
_this.__proto__ = _newTarget.prototype;
|
||||
}
|
||||
return _this;
|
||||
}
|
||||
return ReadFileError;
|
||||
}(Error));
|
||||
exports.ReadFileError = ReadFileError;
|
||||
Generated
Vendored
+10
@@ -0,0 +1,10 @@
|
||||
/***
|
||||
* Node External Editor
|
||||
*
|
||||
* Kevin Gravier <kevin@mrkmg.com>
|
||||
* MIT 2018
|
||||
*/
|
||||
export declare class RemoveFileError extends Error {
|
||||
originalError: Error;
|
||||
constructor(originalError: Error);
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
"use strict";
|
||||
/***
|
||||
* Node External Editor
|
||||
*
|
||||
* Kevin Gravier <kevin@mrkmg.com>
|
||||
* MIT 2018
|
||||
*/
|
||||
var __extends = (this && this.__extends) || (function () {
|
||||
var extendStatics = function (d, b) {
|
||||
extendStatics = Object.setPrototypeOf ||
|
||||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
|
||||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
|
||||
return extendStatics(d, b);
|
||||
};
|
||||
return function (d, b) {
|
||||
extendStatics(d, b);
|
||||
function __() { this.constructor = d; }
|
||||
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
|
||||
};
|
||||
})();
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
var RemoveFileError = /** @class */ (function (_super) {
|
||||
__extends(RemoveFileError, _super);
|
||||
function RemoveFileError(originalError) {
|
||||
var _newTarget = this.constructor;
|
||||
var _this = _super.call(this, "Failed to cleanup temporary file") || this;
|
||||
_this.originalError = originalError;
|
||||
var proto = _newTarget.prototype;
|
||||
if (Object.setPrototypeOf) {
|
||||
Object.setPrototypeOf(_this, proto);
|
||||
}
|
||||
else {
|
||||
_this.__proto__ = _newTarget.prototype;
|
||||
}
|
||||
return _this;
|
||||
}
|
||||
return RemoveFileError;
|
||||
}(Error));
|
||||
exports.RemoveFileError = RemoveFileError;
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
/***
|
||||
* Node External Editor
|
||||
*
|
||||
* Kevin Gravier <kevin@mrkmg.com>
|
||||
* MIT 2019
|
||||
*/
|
||||
import { CreateFileError } from "./errors/CreateFileError";
|
||||
import { LaunchEditorError } from "./errors/LaunchEditorError";
|
||||
import { ReadFileError } from "./errors/ReadFileError";
|
||||
import { RemoveFileError } from "./errors/RemoveFileError";
|
||||
export interface IEditorParams {
|
||||
args: string[];
|
||||
bin: string;
|
||||
}
|
||||
export interface IFileOptions {
|
||||
prefix?: string;
|
||||
postfix?: string;
|
||||
mode?: number;
|
||||
template?: string;
|
||||
dir?: string;
|
||||
}
|
||||
export declare type StringCallback = (err: Error, result: string) => void;
|
||||
export declare type VoidCallback = () => void;
|
||||
export { CreateFileError, LaunchEditorError, ReadFileError, RemoveFileError };
|
||||
export declare function edit(text?: string, fileOptions?: IFileOptions): string;
|
||||
export declare function editAsync(text: string, callback: StringCallback, fileOptions?: IFileOptions): void;
|
||||
export declare class ExternalEditor {
|
||||
private static splitStringBySpace;
|
||||
text: string;
|
||||
tempFile: string;
|
||||
editor: IEditorParams;
|
||||
lastExitStatus: number;
|
||||
private fileOptions;
|
||||
readonly temp_file: string;
|
||||
readonly last_exit_status: number;
|
||||
constructor(text?: string, fileOptions?: IFileOptions);
|
||||
run(): string;
|
||||
runAsync(callback: StringCallback): void;
|
||||
cleanup(): void;
|
||||
private determineEditor;
|
||||
private createTemporaryFile;
|
||||
private readTemporaryFile;
|
||||
private removeTemporaryFile;
|
||||
private launchEditor;
|
||||
private launchEditorAsync;
|
||||
}
|
||||
+193
@@ -0,0 +1,193 @@
|
||||
"use strict";
|
||||
/***
|
||||
* Node External Editor
|
||||
*
|
||||
* Kevin Gravier <kevin@mrkmg.com>
|
||||
* MIT 2019
|
||||
*/
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
var chardet_1 = require("chardet");
|
||||
var child_process_1 = require("child_process");
|
||||
var fs_1 = require("fs");
|
||||
var iconv_lite_1 = require("iconv-lite");
|
||||
var tmp_1 = require("tmp");
|
||||
var CreateFileError_1 = require("./errors/CreateFileError");
|
||||
exports.CreateFileError = CreateFileError_1.CreateFileError;
|
||||
var LaunchEditorError_1 = require("./errors/LaunchEditorError");
|
||||
exports.LaunchEditorError = LaunchEditorError_1.LaunchEditorError;
|
||||
var ReadFileError_1 = require("./errors/ReadFileError");
|
||||
exports.ReadFileError = ReadFileError_1.ReadFileError;
|
||||
var RemoveFileError_1 = require("./errors/RemoveFileError");
|
||||
exports.RemoveFileError = RemoveFileError_1.RemoveFileError;
|
||||
function edit(text, fileOptions) {
|
||||
if (text === void 0) { text = ""; }
|
||||
var editor = new ExternalEditor(text, fileOptions);
|
||||
editor.run();
|
||||
editor.cleanup();
|
||||
return editor.text;
|
||||
}
|
||||
exports.edit = edit;
|
||||
function editAsync(text, callback, fileOptions) {
|
||||
if (text === void 0) { text = ""; }
|
||||
var editor = new ExternalEditor(text, fileOptions);
|
||||
editor.runAsync(function (err, result) {
|
||||
if (err) {
|
||||
setImmediate(callback, err, null);
|
||||
}
|
||||
else {
|
||||
try {
|
||||
editor.cleanup();
|
||||
setImmediate(callback, null, result);
|
||||
}
|
||||
catch (cleanupError) {
|
||||
setImmediate(callback, cleanupError, null);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
exports.editAsync = editAsync;
|
||||
var ExternalEditor = /** @class */ (function () {
|
||||
function ExternalEditor(text, fileOptions) {
|
||||
if (text === void 0) { text = ""; }
|
||||
this.text = "";
|
||||
this.fileOptions = {};
|
||||
this.text = text;
|
||||
if (fileOptions) {
|
||||
this.fileOptions = fileOptions;
|
||||
}
|
||||
this.determineEditor();
|
||||
this.createTemporaryFile();
|
||||
}
|
||||
ExternalEditor.splitStringBySpace = function (str) {
|
||||
var pieces = [];
|
||||
var currentString = "";
|
||||
for (var strIndex = 0; strIndex < str.length; strIndex++) {
|
||||
var currentLetter = str[strIndex];
|
||||
if (strIndex > 0 && currentLetter === " " && str[strIndex - 1] !== "\\" && currentString.length > 0) {
|
||||
pieces.push(currentString);
|
||||
currentString = "";
|
||||
}
|
||||
else {
|
||||
currentString += currentLetter;
|
||||
}
|
||||
}
|
||||
if (currentString.length > 0) {
|
||||
pieces.push(currentString);
|
||||
}
|
||||
return pieces;
|
||||
};
|
||||
Object.defineProperty(ExternalEditor.prototype, "temp_file", {
|
||||
get: function () {
|
||||
console.log("DEPRECATED: temp_file. Use tempFile moving forward.");
|
||||
return this.tempFile;
|
||||
},
|
||||
enumerable: true,
|
||||
configurable: true
|
||||
});
|
||||
Object.defineProperty(ExternalEditor.prototype, "last_exit_status", {
|
||||
get: function () {
|
||||
console.log("DEPRECATED: last_exit_status. Use lastExitStatus moving forward.");
|
||||
return this.lastExitStatus;
|
||||
},
|
||||
enumerable: true,
|
||||
configurable: true
|
||||
});
|
||||
ExternalEditor.prototype.run = function () {
|
||||
this.launchEditor();
|
||||
this.readTemporaryFile();
|
||||
return this.text;
|
||||
};
|
||||
ExternalEditor.prototype.runAsync = function (callback) {
|
||||
var _this = this;
|
||||
try {
|
||||
this.launchEditorAsync(function () {
|
||||
try {
|
||||
_this.readTemporaryFile();
|
||||
setImmediate(callback, null, _this.text);
|
||||
}
|
||||
catch (readError) {
|
||||
setImmediate(callback, readError, null);
|
||||
}
|
||||
});
|
||||
}
|
||||
catch (launchError) {
|
||||
setImmediate(callback, launchError, null);
|
||||
}
|
||||
};
|
||||
ExternalEditor.prototype.cleanup = function () {
|
||||
this.removeTemporaryFile();
|
||||
};
|
||||
ExternalEditor.prototype.determineEditor = function () {
|
||||
var editor = process.env.VISUAL ? process.env.VISUAL :
|
||||
process.env.EDITOR ? process.env.EDITOR :
|
||||
/^win/.test(process.platform) ? "notepad" :
|
||||
"vim";
|
||||
var editorOpts = ExternalEditor.splitStringBySpace(editor).map(function (piece) { return piece.replace("\\ ", " "); });
|
||||
var bin = editorOpts.shift();
|
||||
this.editor = { args: editorOpts, bin: bin };
|
||||
};
|
||||
ExternalEditor.prototype.createTemporaryFile = function () {
|
||||
try {
|
||||
this.tempFile = tmp_1.tmpNameSync(this.fileOptions);
|
||||
var opt = { encoding: "utf8" };
|
||||
if (this.fileOptions.hasOwnProperty("mode")) {
|
||||
opt.mode = this.fileOptions.mode;
|
||||
}
|
||||
fs_1.writeFileSync(this.tempFile, this.text, opt);
|
||||
}
|
||||
catch (createFileError) {
|
||||
throw new CreateFileError_1.CreateFileError(createFileError);
|
||||
}
|
||||
};
|
||||
ExternalEditor.prototype.readTemporaryFile = function () {
|
||||
try {
|
||||
var tempFileBuffer = fs_1.readFileSync(this.tempFile);
|
||||
if (tempFileBuffer.length === 0) {
|
||||
this.text = "";
|
||||
}
|
||||
else {
|
||||
var encoding = chardet_1.detect(tempFileBuffer).toString();
|
||||
if (!iconv_lite_1.encodingExists(encoding)) {
|
||||
// Probably a bad idea, but will at least prevent crashing
|
||||
encoding = "utf8";
|
||||
}
|
||||
this.text = iconv_lite_1.decode(tempFileBuffer, encoding);
|
||||
}
|
||||
}
|
||||
catch (readFileError) {
|
||||
throw new ReadFileError_1.ReadFileError(readFileError);
|
||||
}
|
||||
};
|
||||
ExternalEditor.prototype.removeTemporaryFile = function () {
|
||||
try {
|
||||
fs_1.unlinkSync(this.tempFile);
|
||||
}
|
||||
catch (removeFileError) {
|
||||
throw new RemoveFileError_1.RemoveFileError(removeFileError);
|
||||
}
|
||||
};
|
||||
ExternalEditor.prototype.launchEditor = function () {
|
||||
try {
|
||||
var editorProcess = child_process_1.spawnSync(this.editor.bin, this.editor.args.concat([this.tempFile]), { stdio: "inherit" });
|
||||
this.lastExitStatus = editorProcess.status;
|
||||
}
|
||||
catch (launchError) {
|
||||
throw new LaunchEditorError_1.LaunchEditorError(launchError);
|
||||
}
|
||||
};
|
||||
ExternalEditor.prototype.launchEditorAsync = function (callback) {
|
||||
var _this = this;
|
||||
try {
|
||||
var editorProcess = child_process_1.spawn(this.editor.bin, this.editor.args.concat([this.tempFile]), { stdio: "inherit" });
|
||||
editorProcess.on("exit", function (code) {
|
||||
_this.lastExitStatus = code;
|
||||
setImmediate(callback);
|
||||
});
|
||||
}
|
||||
catch (launchError) {
|
||||
throw new LaunchEditorError_1.LaunchEditorError(launchError);
|
||||
}
|
||||
};
|
||||
return ExternalEditor;
|
||||
}());
|
||||
exports.ExternalEditor = ExternalEditor;
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2014 KARASZI István
|
||||
|
||||
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.
|
||||
+314
@@ -0,0 +1,314 @@
|
||||
# Tmp
|
||||
|
||||
A simple temporary file and directory creator for [node.js.][1]
|
||||
|
||||
[](https://travis-ci.org/raszi/node-tmp)
|
||||
[](https://david-dm.org/raszi/node-tmp)
|
||||
[](https://badge.fury.io/js/tmp)
|
||||
[](https://raszi.github.io/node-tmp/)
|
||||
[](https://snyk.io/test/npm/tmp)
|
||||
|
||||
## About
|
||||
|
||||
This is a [widely used library][2] to create temporary files and directories
|
||||
in a [node.js][1] environment.
|
||||
|
||||
Tmp offers both an asynchronous and a synchronous API. For all API calls, all
|
||||
the parameters are optional. There also exists a promisified version of the
|
||||
API, see (5) under references below.
|
||||
|
||||
Tmp uses crypto for determining random file names, or, when using templates,
|
||||
a six letter random identifier. And just in case that you do not have that much
|
||||
entropy left on your system, Tmp will fall back to pseudo random numbers.
|
||||
|
||||
You can set whether you want to remove the temporary file on process exit or
|
||||
not, and the destination directory can also be set.
|
||||
|
||||
## How to install
|
||||
|
||||
```bash
|
||||
npm install tmp
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
Please also check [API docs][4].
|
||||
|
||||
### Asynchronous file creation
|
||||
|
||||
Simple temporary file creation, the file will be closed and unlinked on process exit.
|
||||
|
||||
```javascript
|
||||
var tmp = require('tmp');
|
||||
|
||||
tmp.file(function _tempFileCreated(err, path, fd, cleanupCallback) {
|
||||
if (err) throw err;
|
||||
|
||||
console.log('File: ', path);
|
||||
console.log('Filedescriptor: ', fd);
|
||||
|
||||
// If we don't need the file anymore we could manually call the cleanupCallback
|
||||
// But that is not necessary if we didn't pass the keep option because the library
|
||||
// will clean after itself.
|
||||
cleanupCallback();
|
||||
});
|
||||
```
|
||||
|
||||
### Synchronous file creation
|
||||
|
||||
A synchronous version of the above.
|
||||
|
||||
```javascript
|
||||
var tmp = require('tmp');
|
||||
|
||||
var tmpobj = tmp.fileSync();
|
||||
console.log('File: ', tmpobj.name);
|
||||
console.log('Filedescriptor: ', tmpobj.fd);
|
||||
|
||||
// If we don't need the file anymore we could manually call the removeCallback
|
||||
// But that is not necessary if we didn't pass the keep option because the library
|
||||
// will clean after itself.
|
||||
tmpobj.removeCallback();
|
||||
```
|
||||
|
||||
Note that this might throw an exception if either the maximum limit of retries
|
||||
for creating a temporary name fails, or, in case that you do not have the permission
|
||||
to write to the directory where the temporary file should be created in.
|
||||
|
||||
### Asynchronous directory creation
|
||||
|
||||
Simple temporary directory creation, it will be removed on process exit.
|
||||
|
||||
If the directory still contains items on process exit, then it won't be removed.
|
||||
|
||||
```javascript
|
||||
var tmp = require('tmp');
|
||||
|
||||
tmp.dir(function _tempDirCreated(err, path, cleanupCallback) {
|
||||
if (err) throw err;
|
||||
|
||||
console.log('Dir: ', path);
|
||||
|
||||
// Manual cleanup
|
||||
cleanupCallback();
|
||||
});
|
||||
```
|
||||
|
||||
If you want to cleanup the directory even when there are entries in it, then
|
||||
you can pass the `unsafeCleanup` option when creating it.
|
||||
|
||||
### Synchronous directory creation
|
||||
|
||||
A synchronous version of the above.
|
||||
|
||||
```javascript
|
||||
var tmp = require('tmp');
|
||||
|
||||
var tmpobj = tmp.dirSync();
|
||||
console.log('Dir: ', tmpobj.name);
|
||||
// Manual cleanup
|
||||
tmpobj.removeCallback();
|
||||
```
|
||||
|
||||
Note that this might throw an exception if either the maximum limit of retries
|
||||
for creating a temporary name fails, or, in case that you do not have the permission
|
||||
to write to the directory where the temporary directory should be created in.
|
||||
|
||||
### Asynchronous filename generation
|
||||
|
||||
It is possible with this library to generate a unique filename in the specified
|
||||
directory.
|
||||
|
||||
```javascript
|
||||
var tmp = require('tmp');
|
||||
|
||||
tmp.tmpName(function _tempNameGenerated(err, path) {
|
||||
if (err) throw err;
|
||||
|
||||
console.log('Created temporary filename: ', path);
|
||||
});
|
||||
```
|
||||
|
||||
### Synchronous filename generation
|
||||
|
||||
A synchronous version of the above.
|
||||
|
||||
```javascript
|
||||
var tmp = require('tmp');
|
||||
|
||||
var name = tmp.tmpNameSync();
|
||||
console.log('Created temporary filename: ', name);
|
||||
```
|
||||
|
||||
## Advanced usage
|
||||
|
||||
### Asynchronous file creation
|
||||
|
||||
Creates a file with mode `0644`, prefix will be `prefix-` and postfix will be `.txt`.
|
||||
|
||||
```javascript
|
||||
var tmp = require('tmp');
|
||||
|
||||
tmp.file({ mode: 0644, prefix: 'prefix-', postfix: '.txt' }, function _tempFileCreated(err, path, fd) {
|
||||
if (err) throw err;
|
||||
|
||||
console.log('File: ', path);
|
||||
console.log('Filedescriptor: ', fd);
|
||||
});
|
||||
```
|
||||
|
||||
### Synchronous file creation
|
||||
|
||||
A synchronous version of the above.
|
||||
|
||||
```javascript
|
||||
var tmp = require('tmp');
|
||||
|
||||
var tmpobj = tmp.fileSync({ mode: 0644, prefix: 'prefix-', postfix: '.txt' });
|
||||
console.log('File: ', tmpobj.name);
|
||||
console.log('Filedescriptor: ', tmpobj.fd);
|
||||
```
|
||||
|
||||
### Controlling the Descriptor
|
||||
|
||||
As a side effect of creating a unique file `tmp` gets a file descriptor that is
|
||||
returned to the user as the `fd` parameter. The descriptor may be used by the
|
||||
application and is closed when the `removeCallback` is invoked.
|
||||
|
||||
In some use cases the application does not need the descriptor, needs to close it
|
||||
without removing the file, or needs to remove the file without closing the
|
||||
descriptor. Two options control how the descriptor is managed:
|
||||
|
||||
* `discardDescriptor` - if `true` causes `tmp` to close the descriptor after the file
|
||||
is created. In this case the `fd` parameter is undefined.
|
||||
* `detachDescriptor` - if `true` causes `tmp` to return the descriptor in the `fd`
|
||||
parameter, but it is the application's responsibility to close it when it is no
|
||||
longer needed.
|
||||
|
||||
```javascript
|
||||
var tmp = require('tmp');
|
||||
|
||||
tmp.file({ discardDescriptor: true }, function _tempFileCreated(err, path, fd, cleanupCallback) {
|
||||
if (err) throw err;
|
||||
// fd will be undefined, allowing application to use fs.createReadStream(path)
|
||||
// without holding an unused descriptor open.
|
||||
});
|
||||
```
|
||||
|
||||
```javascript
|
||||
var tmp = require('tmp');
|
||||
|
||||
tmp.file({ detachDescriptor: true }, function _tempFileCreated(err, path, fd, cleanupCallback) {
|
||||
if (err) throw err;
|
||||
|
||||
cleanupCallback();
|
||||
// Application can store data through fd here; the space used will automatically
|
||||
// be reclaimed by the operating system when the descriptor is closed or program
|
||||
// terminates.
|
||||
});
|
||||
```
|
||||
|
||||
### Asynchronous directory creation
|
||||
|
||||
Creates a directory with mode `0755`, prefix will be `myTmpDir_`.
|
||||
|
||||
```javascript
|
||||
var tmp = require('tmp');
|
||||
|
||||
tmp.dir({ mode: 0750, prefix: 'myTmpDir_' }, function _tempDirCreated(err, path) {
|
||||
if (err) throw err;
|
||||
|
||||
console.log('Dir: ', path);
|
||||
});
|
||||
```
|
||||
|
||||
### Synchronous directory creation
|
||||
|
||||
Again, a synchronous version of the above.
|
||||
|
||||
```javascript
|
||||
var tmp = require('tmp');
|
||||
|
||||
var tmpobj = tmp.dirSync({ mode: 0750, prefix: 'myTmpDir_' });
|
||||
console.log('Dir: ', tmpobj.name);
|
||||
```
|
||||
|
||||
### mkstemp like, asynchronously
|
||||
|
||||
Creates a new temporary directory with mode `0700` and filename like `/tmp/tmp-nk2J1u`.
|
||||
|
||||
```javascript
|
||||
var tmp = require('tmp');
|
||||
|
||||
tmp.dir({ template: '/tmp/tmp-XXXXXX' }, function _tempDirCreated(err, path) {
|
||||
if (err) throw err;
|
||||
|
||||
console.log('Dir: ', path);
|
||||
});
|
||||
```
|
||||
|
||||
### mkstemp like, synchronously
|
||||
|
||||
This will behave similarly to the asynchronous version.
|
||||
|
||||
```javascript
|
||||
var tmp = require('tmp');
|
||||
|
||||
var tmpobj = tmp.dirSync({ template: '/tmp/tmp-XXXXXX' });
|
||||
console.log('Dir: ', tmpobj.name);
|
||||
```
|
||||
|
||||
### Asynchronous filename generation
|
||||
|
||||
The `tmpName()` function accepts the `prefix`, `postfix`, `dir`, etc. parameters also:
|
||||
|
||||
```javascript
|
||||
var tmp = require('tmp');
|
||||
|
||||
tmp.tmpName({ template: '/tmp/tmp-XXXXXX' }, function _tempNameGenerated(err, path) {
|
||||
if (err) throw err;
|
||||
|
||||
console.log('Created temporary filename: ', path);
|
||||
});
|
||||
```
|
||||
|
||||
### Synchronous filename generation
|
||||
|
||||
The `tmpNameSync()` function works similarly to `tmpName()`.
|
||||
|
||||
```javascript
|
||||
var tmp = require('tmp');
|
||||
var tmpname = tmp.tmpNameSync({ template: '/tmp/tmp-XXXXXX' });
|
||||
console.log('Created temporary filename: ', tmpname);
|
||||
```
|
||||
|
||||
## Graceful cleanup
|
||||
|
||||
One may want to cleanup the temporary files even when an uncaught exception
|
||||
occurs. To enforce this, you can call the `setGracefulCleanup()` method:
|
||||
|
||||
```javascript
|
||||
var tmp = require('tmp');
|
||||
|
||||
tmp.setGracefulCleanup();
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
All options are optional :)
|
||||
|
||||
* `mode`: the file mode to create with, it fallbacks to `0600` on file creation and `0700` on directory creation
|
||||
* `prefix`: the optional prefix, fallbacks to `tmp-` if not provided
|
||||
* `postfix`: the optional postfix, fallbacks to `.tmp` on file creation
|
||||
* `template`: [`mkstemp`][3] like filename template, no default
|
||||
* `dir`: the optional temporary directory, fallbacks to system default (guesses from environment)
|
||||
* `tries`: how many times should the function try to get a unique filename before giving up, default `3`
|
||||
* `keep`: signals that the temporary file or directory should not be deleted on exit, default is `false`, means delete
|
||||
* Please keep in mind that it is recommended in this case to call the provided `cleanupCallback` function manually.
|
||||
* `unsafeCleanup`: recursively removes the created temporary directory, even when it's not empty. default is `false`
|
||||
|
||||
[1]: http://nodejs.org/
|
||||
[2]: https://www.npmjs.com/browse/depended/tmp
|
||||
[3]: http://www.kernel.org/doc/man-pages/online/pages/man3/mkstemp.3.html
|
||||
[4]: https://raszi.github.io/node-tmp/
|
||||
[5]: https://github.com/benjamingr/tmp-promise
|
||||
+611
@@ -0,0 +1,611 @@
|
||||
/*!
|
||||
* Tmp
|
||||
*
|
||||
* Copyright (c) 2011-2017 KARASZI Istvan <github@spam.raszi.hu>
|
||||
*
|
||||
* MIT Licensed
|
||||
*/
|
||||
|
||||
/*
|
||||
* Module dependencies.
|
||||
*/
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const crypto = require('crypto');
|
||||
const osTmpDir = require('os-tmpdir');
|
||||
const _c = process.binding('constants');
|
||||
|
||||
/*
|
||||
* The working inner variables.
|
||||
*/
|
||||
const
|
||||
/**
|
||||
* The temporary directory.
|
||||
* @type {string}
|
||||
*/
|
||||
tmpDir = osTmpDir(),
|
||||
|
||||
// the random characters to choose from
|
||||
RANDOM_CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',
|
||||
|
||||
TEMPLATE_PATTERN = /XXXXXX/,
|
||||
|
||||
DEFAULT_TRIES = 3,
|
||||
|
||||
CREATE_FLAGS = (_c.O_CREAT || _c.fs.O_CREAT) | (_c.O_EXCL || _c.fs.O_EXCL) | (_c.O_RDWR || _c.fs.O_RDWR),
|
||||
|
||||
EBADF = _c.EBADF || _c.os.errno.EBADF,
|
||||
ENOENT = _c.ENOENT || _c.os.errno.ENOENT,
|
||||
|
||||
DIR_MODE = 448 /* 0o700 */,
|
||||
FILE_MODE = 384 /* 0o600 */,
|
||||
|
||||
// this will hold the objects need to be removed on exit
|
||||
_removeObjects = [];
|
||||
|
||||
var
|
||||
_gracefulCleanup = false,
|
||||
_uncaughtException = false;
|
||||
|
||||
/**
|
||||
* Random name generator based on crypto.
|
||||
* Adapted from http://blog.tompawlak.org/how-to-generate-random-values-nodejs-javascript
|
||||
*
|
||||
* @param {number} howMany
|
||||
* @returns {string} the generated random name
|
||||
* @private
|
||||
*/
|
||||
function _randomChars(howMany) {
|
||||
var
|
||||
value = [],
|
||||
rnd = null;
|
||||
|
||||
// make sure that we do not fail because we ran out of entropy
|
||||
try {
|
||||
rnd = crypto.randomBytes(howMany);
|
||||
} catch (e) {
|
||||
rnd = crypto.pseudoRandomBytes(howMany);
|
||||
}
|
||||
|
||||
for (var i = 0; i < howMany; i++) {
|
||||
value.push(RANDOM_CHARS[rnd[i] % RANDOM_CHARS.length]);
|
||||
}
|
||||
|
||||
return value.join('');
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether the `obj` parameter is defined or not.
|
||||
*
|
||||
* @param {Object} obj
|
||||
* @returns {boolean} true if the object is undefined
|
||||
* @private
|
||||
*/
|
||||
function _isUndefined(obj) {
|
||||
return typeof obj === 'undefined';
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses the function arguments.
|
||||
*
|
||||
* This function helps to have optional arguments.
|
||||
*
|
||||
* @param {(Options|Function)} options
|
||||
* @param {Function} callback
|
||||
* @returns {Array} parsed arguments
|
||||
* @private
|
||||
*/
|
||||
function _parseArguments(options, callback) {
|
||||
if (typeof options == 'function') {
|
||||
return [callback || {}, options];
|
||||
}
|
||||
|
||||
if (_isUndefined(options)) {
|
||||
return [{}, callback];
|
||||
}
|
||||
|
||||
return [options, callback];
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates a new temporary name.
|
||||
*
|
||||
* @param {Object} opts
|
||||
* @returns {string} the new random name according to opts
|
||||
* @private
|
||||
*/
|
||||
function _generateTmpName(opts) {
|
||||
if (opts.name) {
|
||||
return path.join(opts.dir || tmpDir, opts.name);
|
||||
}
|
||||
|
||||
// mkstemps like template
|
||||
if (opts.template) {
|
||||
return opts.template.replace(TEMPLATE_PATTERN, _randomChars(6));
|
||||
}
|
||||
|
||||
// prefix and postfix
|
||||
const name = [
|
||||
opts.prefix || 'tmp-',
|
||||
process.pid,
|
||||
_randomChars(12),
|
||||
opts.postfix || ''
|
||||
].join('');
|
||||
|
||||
return path.join(opts.dir || tmpDir, name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a temporary file name.
|
||||
*
|
||||
* @param {(Options|tmpNameCallback)} options options or callback
|
||||
* @param {?tmpNameCallback} callback the callback function
|
||||
*/
|
||||
function tmpName(options, callback) {
|
||||
var
|
||||
args = _parseArguments(options, callback),
|
||||
opts = args[0],
|
||||
cb = args[1],
|
||||
tries = opts.name ? 1 : opts.tries || DEFAULT_TRIES;
|
||||
|
||||
if (isNaN(tries) || tries < 0)
|
||||
return cb(new Error('Invalid tries'));
|
||||
|
||||
if (opts.template && !opts.template.match(TEMPLATE_PATTERN))
|
||||
return cb(new Error('Invalid template provided'));
|
||||
|
||||
(function _getUniqueName() {
|
||||
const name = _generateTmpName(opts);
|
||||
|
||||
// check whether the path exists then retry if needed
|
||||
fs.stat(name, function (err) {
|
||||
if (!err) {
|
||||
if (tries-- > 0) return _getUniqueName();
|
||||
|
||||
return cb(new Error('Could not get a unique tmp filename, max tries reached ' + name));
|
||||
}
|
||||
|
||||
cb(null, name);
|
||||
});
|
||||
}());
|
||||
}
|
||||
|
||||
/**
|
||||
* Synchronous version of tmpName.
|
||||
*
|
||||
* @param {Object} options
|
||||
* @returns {string} the generated random name
|
||||
* @throws {Error} if the options are invalid or could not generate a filename
|
||||
*/
|
||||
function tmpNameSync(options) {
|
||||
var
|
||||
args = _parseArguments(options),
|
||||
opts = args[0],
|
||||
tries = opts.name ? 1 : opts.tries || DEFAULT_TRIES;
|
||||
|
||||
if (isNaN(tries) || tries < 0)
|
||||
throw new Error('Invalid tries');
|
||||
|
||||
if (opts.template && !opts.template.match(TEMPLATE_PATTERN))
|
||||
throw new Error('Invalid template provided');
|
||||
|
||||
do {
|
||||
const name = _generateTmpName(opts);
|
||||
try {
|
||||
fs.statSync(name);
|
||||
} catch (e) {
|
||||
return name;
|
||||
}
|
||||
} while (tries-- > 0);
|
||||
|
||||
throw new Error('Could not get a unique tmp filename, max tries reached');
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates and opens a temporary file.
|
||||
*
|
||||
* @param {(Options|fileCallback)} options the config options or the callback function
|
||||
* @param {?fileCallback} callback
|
||||
*/
|
||||
function file(options, callback) {
|
||||
var
|
||||
args = _parseArguments(options, callback),
|
||||
opts = args[0],
|
||||
cb = args[1];
|
||||
|
||||
opts.postfix = (_isUndefined(opts.postfix)) ? '.tmp' : opts.postfix;
|
||||
|
||||
// gets a temporary filename
|
||||
tmpName(opts, function _tmpNameCreated(err, name) {
|
||||
if (err) return cb(err);
|
||||
|
||||
// create and open the file
|
||||
fs.open(name, CREATE_FLAGS, opts.mode || FILE_MODE, function _fileCreated(err, fd) {
|
||||
if (err) return cb(err);
|
||||
|
||||
if (opts.discardDescriptor) {
|
||||
return fs.close(fd, function _discardCallback(err) {
|
||||
if (err) {
|
||||
// Low probability, and the file exists, so this could be
|
||||
// ignored. If it isn't we certainly need to unlink the
|
||||
// file, and if that fails too its error is more
|
||||
// important.
|
||||
try {
|
||||
fs.unlinkSync(name);
|
||||
} catch (e) {
|
||||
if (!isENOENT(e)) {
|
||||
err = e;
|
||||
}
|
||||
}
|
||||
return cb(err);
|
||||
}
|
||||
cb(null, name, undefined, _prepareTmpFileRemoveCallback(name, -1, opts));
|
||||
});
|
||||
}
|
||||
if (opts.detachDescriptor) {
|
||||
return cb(null, name, fd, _prepareTmpFileRemoveCallback(name, -1, opts));
|
||||
}
|
||||
cb(null, name, fd, _prepareTmpFileRemoveCallback(name, fd, opts));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Synchronous version of file.
|
||||
*
|
||||
* @param {Options} options
|
||||
* @returns {FileSyncObject} object consists of name, fd and removeCallback
|
||||
* @throws {Error} if cannot create a file
|
||||
*/
|
||||
function fileSync(options) {
|
||||
var
|
||||
args = _parseArguments(options),
|
||||
opts = args[0];
|
||||
|
||||
opts.postfix = opts.postfix || '.tmp';
|
||||
|
||||
const discardOrDetachDescriptor = opts.discardDescriptor || opts.detachDescriptor;
|
||||
const name = tmpNameSync(opts);
|
||||
var fd = fs.openSync(name, CREATE_FLAGS, opts.mode || FILE_MODE);
|
||||
if (opts.discardDescriptor) {
|
||||
fs.closeSync(fd);
|
||||
fd = undefined;
|
||||
}
|
||||
|
||||
return {
|
||||
name: name,
|
||||
fd: fd,
|
||||
removeCallback: _prepareTmpFileRemoveCallback(name, discardOrDetachDescriptor ? -1 : fd, opts)
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes files and folders in a directory recursively.
|
||||
*
|
||||
* @param {string} root
|
||||
* @private
|
||||
*/
|
||||
function _rmdirRecursiveSync(root) {
|
||||
const dirs = [root];
|
||||
|
||||
do {
|
||||
var
|
||||
dir = dirs.pop(),
|
||||
deferred = false,
|
||||
files = fs.readdirSync(dir);
|
||||
|
||||
for (var i = 0, length = files.length; i < length; i++) {
|
||||
var
|
||||
file = path.join(dir, files[i]),
|
||||
stat = fs.lstatSync(file); // lstat so we don't recurse into symlinked directories
|
||||
|
||||
if (stat.isDirectory()) {
|
||||
if (!deferred) {
|
||||
deferred = true;
|
||||
dirs.push(dir);
|
||||
}
|
||||
dirs.push(file);
|
||||
} else {
|
||||
fs.unlinkSync(file);
|
||||
}
|
||||
}
|
||||
|
||||
if (!deferred) {
|
||||
fs.rmdirSync(dir);
|
||||
}
|
||||
} while (dirs.length !== 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a temporary directory.
|
||||
*
|
||||
* @param {(Options|dirCallback)} options the options or the callback function
|
||||
* @param {?dirCallback} callback
|
||||
*/
|
||||
function dir(options, callback) {
|
||||
var
|
||||
args = _parseArguments(options, callback),
|
||||
opts = args[0],
|
||||
cb = args[1];
|
||||
|
||||
// gets a temporary filename
|
||||
tmpName(opts, function _tmpNameCreated(err, name) {
|
||||
if (err) return cb(err);
|
||||
|
||||
// create the directory
|
||||
fs.mkdir(name, opts.mode || DIR_MODE, function _dirCreated(err) {
|
||||
if (err) return cb(err);
|
||||
|
||||
cb(null, name, _prepareTmpDirRemoveCallback(name, opts));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Synchronous version of dir.
|
||||
*
|
||||
* @param {Options} options
|
||||
* @returns {DirSyncObject} object consists of name and removeCallback
|
||||
* @throws {Error} if it cannot create a directory
|
||||
*/
|
||||
function dirSync(options) {
|
||||
var
|
||||
args = _parseArguments(options),
|
||||
opts = args[0];
|
||||
|
||||
const name = tmpNameSync(opts);
|
||||
fs.mkdirSync(name, opts.mode || DIR_MODE);
|
||||
|
||||
return {
|
||||
name: name,
|
||||
removeCallback: _prepareTmpDirRemoveCallback(name, opts)
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepares the callback for removal of the temporary file.
|
||||
*
|
||||
* @param {string} name the path of the file
|
||||
* @param {number} fd file descriptor
|
||||
* @param {Object} opts
|
||||
* @returns {fileCallback}
|
||||
* @private
|
||||
*/
|
||||
function _prepareTmpFileRemoveCallback(name, fd, opts) {
|
||||
const removeCallback = _prepareRemoveCallback(function _removeCallback(fdPath) {
|
||||
try {
|
||||
if (0 <= fdPath[0]) {
|
||||
fs.closeSync(fdPath[0]);
|
||||
}
|
||||
}
|
||||
catch (e) {
|
||||
// under some node/windows related circumstances, a temporary file
|
||||
// may have not be created as expected or the file was already closed
|
||||
// by the user, in which case we will simply ignore the error
|
||||
if (!isEBADF(e) && !isENOENT(e)) {
|
||||
// reraise any unanticipated error
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
try {
|
||||
fs.unlinkSync(fdPath[1]);
|
||||
}
|
||||
catch (e) {
|
||||
if (!isENOENT(e)) {
|
||||
// reraise any unanticipated error
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}, [fd, name]);
|
||||
|
||||
if (!opts.keep) {
|
||||
_removeObjects.unshift(removeCallback);
|
||||
}
|
||||
|
||||
return removeCallback;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepares the callback for removal of the temporary directory.
|
||||
*
|
||||
* @param {string} name
|
||||
* @param {Object} opts
|
||||
* @returns {Function} the callback
|
||||
* @private
|
||||
*/
|
||||
function _prepareTmpDirRemoveCallback(name, opts) {
|
||||
const removeFunction = opts.unsafeCleanup ? _rmdirRecursiveSync : fs.rmdirSync.bind(fs);
|
||||
const removeCallback = _prepareRemoveCallback(removeFunction, name);
|
||||
|
||||
if (!opts.keep) {
|
||||
_removeObjects.unshift(removeCallback);
|
||||
}
|
||||
|
||||
return removeCallback;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a guarded function wrapping the removeFunction call.
|
||||
*
|
||||
* @param {Function} removeFunction
|
||||
* @param {Object} arg
|
||||
* @returns {Function}
|
||||
* @private
|
||||
*/
|
||||
function _prepareRemoveCallback(removeFunction, arg) {
|
||||
var called = false;
|
||||
|
||||
return function _cleanupCallback(next) {
|
||||
if (!called) {
|
||||
const index = _removeObjects.indexOf(_cleanupCallback);
|
||||
if (index >= 0) {
|
||||
_removeObjects.splice(index, 1);
|
||||
}
|
||||
|
||||
called = true;
|
||||
removeFunction(arg);
|
||||
}
|
||||
|
||||
if (next) next(null);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The garbage collector.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
function _garbageCollector() {
|
||||
if (_uncaughtException && !_gracefulCleanup) {
|
||||
return;
|
||||
}
|
||||
|
||||
// the function being called removes itself from _removeObjects,
|
||||
// loop until _removeObjects is empty
|
||||
while (_removeObjects.length) {
|
||||
try {
|
||||
_removeObjects[0].call(null);
|
||||
} catch (e) {
|
||||
// already removed?
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper for testing against EBADF to compensate changes made to Node 7.x under Windows.
|
||||
*/
|
||||
function isEBADF(error) {
|
||||
return isExpectedError(error, -EBADF, 'EBADF');
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper for testing against ENOENT to compensate changes made to Node 7.x under Windows.
|
||||
*/
|
||||
function isENOENT(error) {
|
||||
return isExpectedError(error, -ENOENT, 'ENOENT');
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper to determine whether the expected error code matches the actual code and errno,
|
||||
* which will differ between the supported node versions.
|
||||
*
|
||||
* - Node >= 7.0:
|
||||
* error.code {String}
|
||||
* error.errno {String|Number} any numerical value will be negated
|
||||
*
|
||||
* - Node >= 6.0 < 7.0:
|
||||
* error.code {String}
|
||||
* error.errno {Number} negated
|
||||
*
|
||||
* - Node >= 4.0 < 6.0: introduces SystemError
|
||||
* error.code {String}
|
||||
* error.errno {Number} negated
|
||||
*
|
||||
* - Node >= 0.10 < 4.0:
|
||||
* error.code {Number} negated
|
||||
* error.errno n/a
|
||||
*/
|
||||
function isExpectedError(error, code, errno) {
|
||||
return error.code == code || error.code == errno;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the graceful cleanup.
|
||||
*
|
||||
* Also removes the created files and directories when an uncaught exception occurs.
|
||||
*/
|
||||
function setGracefulCleanup() {
|
||||
_gracefulCleanup = true;
|
||||
}
|
||||
|
||||
const version = process.versions.node.split('.').map(function (value) {
|
||||
return parseInt(value, 10);
|
||||
});
|
||||
|
||||
if (version[0] === 0 && (version[1] < 9 || version[1] === 9 && version[2] < 5)) {
|
||||
process.addListener('uncaughtException', function _uncaughtExceptionThrown(err) {
|
||||
_uncaughtException = true;
|
||||
_garbageCollector();
|
||||
|
||||
throw err;
|
||||
});
|
||||
}
|
||||
|
||||
process.addListener('exit', function _exit(code) {
|
||||
if (code) _uncaughtException = true;
|
||||
_garbageCollector();
|
||||
});
|
||||
|
||||
/**
|
||||
* Configuration options.
|
||||
*
|
||||
* @typedef {Object} Options
|
||||
* @property {?number} tries the number of tries before give up the name generation
|
||||
* @property {?string} template the "mkstemp" like filename template
|
||||
* @property {?string} name fix name
|
||||
* @property {?string} dir the tmp directory to use
|
||||
* @property {?string} prefix prefix for the generated name
|
||||
* @property {?string} postfix postfix for the generated name
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {Object} FileSyncObject
|
||||
* @property {string} name the name of the file
|
||||
* @property {string} fd the file descriptor
|
||||
* @property {fileCallback} removeCallback the callback function to remove the file
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {Object} DirSyncObject
|
||||
* @property {string} name the name of the directory
|
||||
* @property {fileCallback} removeCallback the callback function to remove the directory
|
||||
*/
|
||||
|
||||
/**
|
||||
* @callback tmpNameCallback
|
||||
* @param {?Error} err the error object if anything goes wrong
|
||||
* @param {string} name the temporary file name
|
||||
*/
|
||||
|
||||
/**
|
||||
* @callback fileCallback
|
||||
* @param {?Error} err the error object if anything goes wrong
|
||||
* @param {string} name the temporary file name
|
||||
* @param {number} fd the file descriptor
|
||||
* @param {cleanupCallback} fn the cleanup callback function
|
||||
*/
|
||||
|
||||
/**
|
||||
* @callback dirCallback
|
||||
* @param {?Error} err the error object if anything goes wrong
|
||||
* @param {string} name the temporary file name
|
||||
* @param {cleanupCallback} fn the cleanup callback function
|
||||
*/
|
||||
|
||||
/**
|
||||
* Removes the temporary created file or directory.
|
||||
*
|
||||
* @callback cleanupCallback
|
||||
* @param {simpleCallback} [next] function to call after entry was removed
|
||||
*/
|
||||
|
||||
/**
|
||||
* Callback function for function composition.
|
||||
* @see {@link https://github.com/raszi/node-tmp/issues/57|raszi/node-tmp#57}
|
||||
*
|
||||
* @callback simpleCallback
|
||||
*/
|
||||
|
||||
// exporting all the needed methods
|
||||
module.exports.tmpdir = tmpDir;
|
||||
|
||||
module.exports.dir = dir;
|
||||
module.exports.dirSync = dirSync;
|
||||
|
||||
module.exports.file = file;
|
||||
module.exports.fileSync = fileSync;
|
||||
|
||||
module.exports.tmpName = tmpName;
|
||||
module.exports.tmpNameSync = tmpNameSync;
|
||||
|
||||
module.exports.setGracefulCleanup = setGracefulCleanup;
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
{
|
||||
"name": "tmp",
|
||||
"version": "0.0.33",
|
||||
"description": "Temporary file and directory creator",
|
||||
"author": "KARASZI István <github@spam.raszi.hu> (http://raszi.hu/)",
|
||||
"keywords": [
|
||||
"temporary",
|
||||
"tmp",
|
||||
"temp",
|
||||
"tempdir",
|
||||
"tempfile",
|
||||
"tmpdir",
|
||||
"tmpfile"
|
||||
],
|
||||
"license": "MIT",
|
||||
"repository": "raszi/node-tmp",
|
||||
"homepage": "http://github.com/raszi/node-tmp",
|
||||
"bugs": {
|
||||
"url": "http://github.com/raszi/node-tmp/issues"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.6.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"os-tmpdir": "~1.0.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"vows": "~0.7.0"
|
||||
},
|
||||
"main": "lib/tmp.js",
|
||||
"files": [
|
||||
"lib/"
|
||||
],
|
||||
"scripts": {
|
||||
"test": "vows test/*-test.js",
|
||||
"doc": "jsdoc -c .jsdoc.json"
|
||||
}
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
{
|
||||
"name": "external-editor",
|
||||
"version": "3.1.0",
|
||||
"description": "Edit a string with the users preferred text editor using $VISUAL or $ENVIRONMENT",
|
||||
"main": "main/index.js",
|
||||
"types": "main/index.d.ts",
|
||||
"scripts": {
|
||||
"test": "mocha --recursive --require ts-node/register --timeout 10000 ./test/spec 'test/spec/**/*.ts'",
|
||||
"compile": "tsc -p tsconfig.json",
|
||||
"lint": "tslint './src/**/*.ts' './test/**/*.ts'"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/mrkmg/node-external-editor.git"
|
||||
},
|
||||
"keywords": [
|
||||
"editor",
|
||||
"external",
|
||||
"user",
|
||||
"visual"
|
||||
],
|
||||
"author": "Kevin Gravier <kevin@mrkmg.com> (https://mrkmg.com)",
|
||||
"license": "MIT",
|
||||
"bugs": {
|
||||
"url": "https://github.com/mrkmg/node-external-editor/issues"
|
||||
},
|
||||
"homepage": "https://github.com/mrkmg/node-external-editor#readme",
|
||||
"dependencies": {
|
||||
"chardet": "^0.7.0",
|
||||
"iconv-lite": "^0.4.24",
|
||||
"tmp": "^0.0.33"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/chai": "^4.1.4",
|
||||
"@types/chardet": "^0.5.0",
|
||||
"@types/mocha": "^5.2.5",
|
||||
"@types/node": "^10.14.12",
|
||||
"@types/tmp": "0.0.33",
|
||||
"chai": "^4.0.0",
|
||||
"es6-shim": "^0.35.3",
|
||||
"mocha": "^5.2.0",
|
||||
"ts-node": "^7.0.1",
|
||||
"tslint": "^5.18.0",
|
||||
"typescript": "^3.5.2"
|
||||
},
|
||||
"files": [
|
||||
"main",
|
||||
"example_sync.js",
|
||||
"example_async.js"
|
||||
],
|
||||
"config": {
|
||||
"ndt": {
|
||||
"versions": [
|
||||
"major"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user