This commit is contained in:
Tutur33
2023-11-24 22:35:41 +01:00
parent 3c0b507a93
commit 7644b2a0f7
45165 changed files with 4803356 additions and 3 deletions
+50
View File
@@ -0,0 +1,50 @@
import { PackageJson } from 'mrm-core';
import { AppEnvironments } from '@ioc:Adonis/Core/Application';
/**
* Shape of the template node
*/
export type TemplateNode = {
src: string;
dest: string;
data?: any;
mustache?: boolean;
} | string;
/**
* Shape of the package instructions node
*/
export type PackageInstructionsBlock = {
instructions?: string;
instructionsMd?: string;
templates?: {
basePath?: string;
} & {
[templateFor: string]: TemplateNode | TemplateNode[];
};
env?: {
[key: string]: string;
};
preloads?: (string | {
file: string;
environment?: AppEnvironments[];
optional?: boolean;
})[];
metaFiles?: (string | {
pattern: string;
reloadServer?: boolean;
})[];
types?: string;
commands?: string[];
providers?: string[];
aliases?: {
[key: string]: string;
};
aceProviders?: string[];
testProviders?: string[];
};
/**
* Shape of the package file along with the adonisjs
* block
*/
export type PackageFile = PackageJson & {
adonisjs: PackageInstructionsBlock;
};
+10
View File
@@ -0,0 +1,10 @@
"use strict";
/*
* @adonisjs/sink
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
+46
View File
@@ -0,0 +1,46 @@
/**
* Base file exposes the API to add action and `cd` in/out from
* the application base directory.
*/
export declare abstract class File {
private basePath;
protected abstract actions: {
action: string;
body?: any;
}[];
/**
* The user current working directory reference. This is maintained, since
* we virtually cd into the `basePath`.
*/
private currentDir;
constructor(basePath: string);
/**
* Add a new action to the actions stack. The action workings
* are independent on the user adding the action
*/
protected addAction(action: string, body?: any): void;
/**
* Returns an array of actions to commit
*/
protected getCommitActions(): {
action: string;
body?: any;
}[];
/**
* Returns an array of actions for performing revert. Since
* reverts are done in reverse, this method will reverse
* the actions array.
*/
protected getRevertActions(): {
action: string;
body?: any;
}[];
/**
* `cd` to the application base path
*/
protected cdIn(): void;
/**
* `cd` out from the application base path
*/
protected cdOut(): void;
}
+55
View File
@@ -0,0 +1,55 @@
"use strict";
/*
* @adonisjs/sink
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.File = void 0;
/**
* Base file exposes the API to add action and `cd` in/out from
* the application base directory.
*/
class File {
constructor(basePath) {
this.basePath = basePath;
}
/**
* Add a new action to the actions stack. The action workings
* are independent on the user adding the action
*/
addAction(action, body) {
this.actions.push({ action, body });
}
/**
* Returns an array of actions to commit
*/
getCommitActions() {
return this.actions;
}
/**
* Returns an array of actions for performing revert. Since
* reverts are done in reverse, this method will reverse
* the actions array.
*/
getRevertActions() {
return this.actions.slice().reverse();
}
/**
* `cd` to the application base path
*/
cdIn() {
this.currentDir = process.cwd();
process.chdir(this.basePath);
}
/**
* `cd` out from the application base path
*/
cdOut() {
process.chdir(this.currentDir);
}
}
exports.File = File;
+43
View File
@@ -0,0 +1,43 @@
import { json, yaml, ini } from 'mrm-core';
import { File } from './File';
/**
* Exposes the API to work with key/value pair files like `ini`, `yaml`
* and `json`.
*/
export declare abstract class KeyValuePair extends File {
protected actions: never[];
/**
* Only these key-value pair files are supported
*/
abstract filePointer: ReturnType<typeof json> | ReturnType<typeof yaml> | ReturnType<typeof ini>;
constructor(basePath: string);
/**
* Set key/value pair
*/
set(key: string, value: any): this;
/**
* Unset key/value pair
*/
unset(key: string): this;
/**
* Remove file
*/
delete(): this;
/**
* Returns value for a given key from the file
*/
get(): any;
get(address: string | string[], defaultValue?: any): any;
/**
* A boolean telling if the file already exists
*/
exists(): boolean;
/**
* Commit mutations
*/
commit(): void;
/**
* Rollback mutations
*/
rollback(): void;
}
+114
View File
@@ -0,0 +1,114 @@
"use strict";
/*
* @adonisjs/sink
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.KeyValuePair = void 0;
const File_1 = require("./File");
/**
* Exposes the API to work with key/value pair files like `ini`, `yaml`
* and `json`.
*/
class KeyValuePair extends File_1.File {
constructor(basePath) {
super(basePath);
this.actions = [];
}
/**
* Set key/value pair
*/
set(key, value) {
this.addAction('set', { key, value });
return this;
}
/**
* Unset key/value pair
*/
unset(key) {
this.addAction('unset', { key });
return this;
}
/**
* Remove file
*/
delete() {
this.addAction('delete');
return this;
}
get(address, defaultValue) {
return address ? this.filePointer.get(address, defaultValue) : this.filePointer.get();
}
/**
* A boolean telling if the file already exists
*/
exists() {
return this.filePointer.exists();
}
/**
* Commit mutations
*/
commit() {
this.cdIn();
const actions = this.getCommitActions();
const deleteFile = actions.find(({ action }) => action === 'delete');
/**
* In case of `delete` action. There is no point running
* other actions and we can simply delete the file
*/
if (deleteFile) {
this.filePointer.delete();
this.cdOut();
return;
}
actions.forEach(({ action, body }) => {
if (typeof this[`on${action}`] === 'function') {
const handled = this[`on${action}`]('commit', body);
/**
* Return early when action is handled by the hook
*/
if (handled) {
return;
}
}
if (action === 'set') {
this.filePointer.set(body.key, body.value);
return;
}
if (action === 'unset') {
this.filePointer.unset(body.key);
}
});
this.filePointer.save();
this.cdOut();
}
/**
* Rollback mutations
*/
rollback() {
this.cdIn();
const actions = this.getRevertActions();
actions.forEach(({ action, body }) => {
if (typeof this[`on${action}`] === 'function') {
const handled = this[`on${action}`]('rollback', body);
/**
* Return early when action is handled by the hook
*/
if (handled) {
return;
}
}
if (action === 'set') {
this.filePointer.unset(body.key);
return;
}
});
this.filePointer.save();
this.cdOut();
}
}
exports.KeyValuePair = KeyValuePair;
+31
View File
@@ -0,0 +1,31 @@
import { ini } from 'mrm-core';
import { KeyValuePair } from '../Base/KeyValuePair';
/**
* Ini file to work with files like `.editorconfig`.
*
* ```ts
* const ini = new Ini(__dirname, '.editorconfig')
* ini.set('_global', { root: true })
* ini.set('**.js', { insert_final_newline: true })
*
* ini.commit()
* ```
*/
export declare class IniFile extends KeyValuePair {
filePointer: ReturnType<typeof ini>;
constructor(basePath: string, filename: string);
/**
* Handling the onmerge action. This method is called by
* the `commit` method.
*/
onmerge(lifecycle: string, body: any): true | undefined;
/**
* Merge to the section values of an ini file.
*
* @example
* ```ts
* ini.merge('root', { indent_style: space })
* ```
*/
merge(section: string, values: any): this;
}
+71
View File
@@ -0,0 +1,71 @@
"use strict";
/*
* @adonisjs/sink
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.IniFile = void 0;
const mrm_core_1 = require("mrm-core");
const KeyValuePair_1 = require("../Base/KeyValuePair");
/**
* Ini file to work with files like `.editorconfig`.
*
* ```ts
* const ini = new Ini(__dirname, '.editorconfig')
* ini.set('_global', { root: true })
* ini.set('**.js', { insert_final_newline: true })
*
* ini.commit()
* ```
*/
class IniFile extends KeyValuePair_1.KeyValuePair {
constructor(basePath, filename) {
super(basePath);
/**
* The `ini` function from `mrm-core` relies on the current
* working directory, that's why we have to cd in to the
* base path before creating a new instance of it.
*/
this.cdIn();
this.filePointer = (0, mrm_core_1.ini)(filename);
this.cdOut();
}
/**
* Handling the onmerge action. This method is called by
* the `commit` method.
*/
onmerge(lifecycle, body) {
if (lifecycle === 'commit') {
this.filePointer.set(body.section, Object.assign({}, this.get(body.section), body.values));
return true;
}
if (lifecycle === 'rollback') {
const resetObject = Object.keys(body.values).reduce((result, key) => {
result[key] = undefined;
return result;
}, {});
this.filePointer.set(body.section, Object.assign({}, this.get(body.section), resetObject));
return true;
}
}
/**
* Merge to the section values of an ini file.
*
* @example
* ```ts
* ini.merge('root', { indent_style: space })
* ```
*/
merge(section, values) {
if (typeof values !== 'object' || values === null) {
return this;
}
this.addAction('merge', { section, values });
return this;
}
}
exports.IniFile = IniFile;
+16
View File
@@ -0,0 +1,16 @@
import { json } from 'mrm-core';
import { KeyValuePair } from '../Base/KeyValuePair';
/**
* Exposes the API to work with JSON files.
*
* ```ts
* const json = new JsonFile(__dirname, 'tsconfig.json')
* json.set('compilerOptions.lib', ['es2017'])
*
* json.commit()
* ```
*/
export declare class JsonFile extends KeyValuePair {
filePointer: ReturnType<typeof json>;
constructor(basePath: string, filename: string);
}
+32
View File
@@ -0,0 +1,32 @@
"use strict";
/*
* @adonisjs/sink
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.JsonFile = void 0;
const mrm_core_1 = require("mrm-core");
const KeyValuePair_1 = require("../Base/KeyValuePair");
/**
* Exposes the API to work with JSON files.
*
* ```ts
* const json = new JsonFile(__dirname, 'tsconfig.json')
* json.set('compilerOptions.lib', ['es2017'])
*
* json.commit()
* ```
*/
class JsonFile extends KeyValuePair_1.KeyValuePair {
constructor(basePath, filename) {
super(basePath);
this.cdIn();
this.filePointer = (0, mrm_core_1.json)(filename);
this.cdOut();
}
}
exports.JsonFile = JsonFile;
+50
View File
@@ -0,0 +1,50 @@
import { file } from 'mrm-core';
import { File } from '../Base/File';
/**
* Exposes the API to generate source files from template files.
*/
export declare class MustacheFile extends File {
private templatePath;
private partialsPaths;
private templateData;
protected actions: never[];
filePointer: ReturnType<typeof file>;
removeOnRollback: boolean;
overwrite: boolean;
constructor(basePath: string, filename: string, templatePath: string);
/**
* Returns a key-value pair of partial names and their contents
*/
private getPartials;
/**
* Returns the contents of the template file
*/
private readTemplate;
/**
* Returns existing contents for a template file
*/
get(): string;
/**
* A boolean telling if the file already exists
*/
exists(): boolean;
/**
* Define one or more partials by defining key-value
* pair of partial name and path to the file.
*/
partials(partials: {
[key: string]: string;
}): this;
/**
* Apply contents to the template to evaluate it's output
*/
apply(contents?: any): this;
/**
* Commit changes
*/
commit(): void;
/**
* Rollback changes
*/
rollback(): void;
}
+124
View File
@@ -0,0 +1,124 @@
"use strict";
/*
* @adonisjs/sink
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.MustacheFile = void 0;
const mustache_1 = __importDefault(require("mustache"));
const mrm_core_1 = require("mrm-core");
const fs_1 = require("fs");
const File_1 = require("../Base/File");
/**
* Exposes the API to generate source files from template files.
*/
class MustacheFile extends File_1.File {
constructor(basePath, filename, templatePath) {
super(basePath);
this.templatePath = templatePath;
this.partialsPaths = {};
this.templateData = {};
this.actions = [];
this.removeOnRollback = true;
this.overwrite = false;
this.cdIn();
this.filePointer = (0, mrm_core_1.file)(filename);
this.cdOut();
}
/**
* Returns a key-value pair of partial names and their contents
*/
getPartials() {
return Object.keys(this.partialsPaths).reduce((result, name) => {
result[name] = this.readTemplate(this.partialsPaths[name]);
return result;
}, {});
}
/**
* Returns the contents of the template file
*/
readTemplate(templatePath) {
try {
return (0, fs_1.readFileSync)(templatePath, 'utf8');
}
catch (err) {
if (err.code === 'ENOENT') {
throw Error(`Template file not found: ${templatePath}`);
}
else {
throw err;
}
}
}
/**
* Returns existing contents for a template file
*/
get() {
return this.filePointer.get();
}
/**
* A boolean telling if the file already exists
*/
exists() {
return this.filePointer.exists();
}
/**
* Define one or more partials by defining key-value
* pair of partial name and path to the file.
*/
partials(partials) {
this.partialsPaths = partials;
return this;
}
/**
* Apply contents to the template to evaluate it's output
*/
apply(contents) {
this.templateData = contents || {};
return this;
}
/**
* Commit changes
*/
commit() {
this.cdIn();
/**
* Do not overwrite contents when file already exists and
* `overwrite = false`
*/
if (this.filePointer.exists() && !this.overwrite) {
this.cdOut();
return;
}
try {
this.filePointer.save(mustache_1.default.render(this.readTemplate(this.templatePath), this.templateData, this.getPartials()));
this.cdOut();
}
catch (error) {
this.cdOut();
throw error;
}
}
/**
* Rollback changes
*/
rollback() {
this.cdIn();
/**
* Remove the file on rollback (only when instructed) or this method results
* is a noop
*/
if (this.filePointer.exists() && this.removeOnRollback) {
this.filePointer.delete();
}
this.cdOut();
}
}
exports.MustacheFile = MustacheFile;
+43
View File
@@ -0,0 +1,43 @@
import { lines } from 'mrm-core';
import { File } from '../Base/File';
/**
* Base class to work with raw text new line files. For example `.env`
* file or `.gitignore`
*/
export declare class NewLineFile extends File {
filePointer: ReturnType<typeof lines>;
protected actions: never[];
constructor(basePath: string, filename: string);
/**
* Add one or more new lines
*/
add(line: string | string[]): this;
/**
* Update existing text with new text
*/
update(oldText: string, newText: string): this;
/**
* Remove lines matching the give text
*/
remove(line: string | string[]): this;
/**
* Delete file
*/
delete(): this;
/**
* Get contents for the file
*/
get(): string[];
/**
* A boolean telling if the file already exists
*/
exists(): boolean;
/**
* Commit mutations
*/
commit(): void;
/**
* Rollback mutations
*/
rollback(): void;
}
+144
View File
@@ -0,0 +1,144 @@
"use strict";
/*
* @adonisjs/sink
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.NewLineFile = void 0;
const mrm_core_1 = require("mrm-core");
const File_1 = require("../Base/File");
/**
* Base class to work with raw text new line files. For example `.env`
* file or `.gitignore`
*/
class NewLineFile extends File_1.File {
constructor(basePath, filename) {
super(basePath);
this.actions = [];
this.cdIn();
this.filePointer = (0, mrm_core_1.lines)(filename);
this.cdOut();
}
/**
* Add one or more new lines
*/
add(line) {
this.addAction('add', { line });
return this;
}
/**
* Update existing text with new text
*/
update(oldText, newText) {
this.addAction('update', { oldText, newText });
return this;
}
/**
* Remove lines matching the give text
*/
remove(line) {
this.addAction('remove', { line });
return this;
}
/**
* Delete file
*/
delete() {
this.addAction('delete');
return this;
}
/**
* Get contents for the file
*/
get() {
return this.filePointer.get();
}
/**
* A boolean telling if the file already exists
*/
exists() {
return this.filePointer.exists();
}
/**
* Commit mutations
*/
commit() {
this.cdIn();
const actions = this.getCommitActions();
const deleteFile = actions.find(({ action }) => action === 'delete');
/**
* In case of `delete` action. There is no point running
* other actions and we can simply delete the file
*/
if (deleteFile) {
this.filePointer.delete();
this.cdOut();
return;
}
actions.forEach(({ action, body }) => {
if (typeof this[`on${action}`] === 'function') {
const handled = this[`on${action}`]('commit', body);
/**
* Return early when action is handled by the hook
*/
if (handled) {
return;
}
}
if (action === 'add') {
this.filePointer.add(body.line);
return;
}
/**
* On update we remove the old line and add the new one
*/
if (action === 'update') {
this.filePointer.remove(body.oldText);
this.filePointer.add(body.newText);
return;
}
if (action === 'remove') {
this.filePointer.remove(body.line);
}
});
this.filePointer.save();
this.cdOut();
}
/**
* Rollback mutations
*/
rollback() {
this.cdIn();
const actions = this.getRevertActions();
actions.forEach(({ action, body }) => {
if (typeof this[`on${action}`] === 'function') {
const handled = this[`on${action}`]('rollback', body);
/**
* Return early when action is handled by the hook
*/
if (handled) {
return;
}
}
if (action === 'add') {
this.filePointer.remove(body.line);
return;
}
if (action === 'update') {
this.filePointer.remove(body.newText);
this.filePointer.add(body.oldText);
return;
}
if (action === 'remove') {
this.filePointer.add(body.line);
}
});
this.filePointer.save();
this.cdOut();
}
}
exports.NewLineFile = NewLineFile;
@@ -0,0 +1,32 @@
import { template } from 'mrm-core';
import { File } from '../Base/File';
/**
* Exposes the API to generate source files from template files.
*/
export declare class TemplateLiteralFile extends File {
protected actions: never[];
filePointer: ReturnType<typeof template>;
removeOnRollback: boolean;
overwrite: boolean;
constructor(basePath: string, filename: string, templatePath: string);
/**
* Returns existing contents for a template file
*/
get(): string;
/**
* A boolean telling if the file already exists
*/
exists(): boolean;
/**
* Apply contents to the template to evaluate it's output
*/
apply(contents?: any): this;
/**
* Commit changes
*/
commit(): void;
/**
* Rollback changes
*/
rollback(): void;
}
+77
View File
@@ -0,0 +1,77 @@
"use strict";
/*
* @adonisjs/sink
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.TemplateLiteralFile = void 0;
const mrm_core_1 = require("mrm-core");
const File_1 = require("../Base/File");
/**
* Exposes the API to generate source files from template files.
*/
class TemplateLiteralFile extends File_1.File {
constructor(basePath, filename, templatePath) {
super(basePath);
this.actions = [];
this.removeOnRollback = true;
this.overwrite = false;
this.cdIn();
this.filePointer = (0, mrm_core_1.template)(filename, templatePath);
this.cdOut();
}
/**
* Returns existing contents for a template file
*/
get() {
return this.filePointer.get();
}
/**
* A boolean telling if the file already exists
*/
exists() {
return this.filePointer.exists();
}
/**
* Apply contents to the template to evaluate it's output
*/
apply(contents) {
this.filePointer.apply(contents);
return this;
}
/**
* Commit changes
*/
commit() {
this.cdIn();
/**
* Do not overwrite contents when file already exists and
* `overwrite = false`
*/
if (this.filePointer.exists() && !this.overwrite) {
this.cdOut();
return;
}
this.filePointer.save();
this.cdOut();
}
/**
* Rollback changes
*/
rollback() {
this.cdIn();
/**
* Remove the file on rollback (only when instructed) or this method results
* is a noop
*/
if (this.filePointer.exists() && this.removeOnRollback) {
this.filePointer.delete();
}
this.cdOut();
}
}
exports.TemplateLiteralFile = TemplateLiteralFile;
+17
View File
@@ -0,0 +1,17 @@
import { yaml } from 'mrm-core';
import { KeyValuePair } from '../Base/KeyValuePair';
/**
* Exposes the API to work with Yaml files.
*
* ```ts
* const yaml = new YamlFile(__dirname, '.travis.yml')
* yaml.set('language', 'node_js')
* yaml.set('language', [4, 6])
*
* yaml.commit()
* ```
*/
export declare class YamlFile extends KeyValuePair {
filePointer: ReturnType<typeof yaml>;
constructor(basePath: string, filename: string);
}
+33
View File
@@ -0,0 +1,33 @@
"use strict";
/*
* @adonisjs/sink
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.YamlFile = void 0;
const mrm_core_1 = require("mrm-core");
const KeyValuePair_1 = require("../Base/KeyValuePair");
/**
* Exposes the API to work with Yaml files.
*
* ```ts
* const yaml = new YamlFile(__dirname, '.travis.yml')
* yaml.set('language', 'node_js')
* yaml.set('language', [4, 6])
*
* yaml.commit()
* ```
*/
class YamlFile extends KeyValuePair_1.KeyValuePair {
constructor(basePath, filename) {
super(basePath);
this.cdIn();
this.filePointer = (0, mrm_core_1.yaml)(filename);
this.cdOut();
}
}
exports.YamlFile = YamlFile;
+80
View File
@@ -0,0 +1,80 @@
import { AppEnvironments } from '@ioc:Adonis/Core/Application';
import { JsonFile } from '../Formats/Json';
/**
* Exposes API to mutate the contents of `.adonisrc.json` file.
*/
export declare class AdonisRcFile extends JsonFile {
/**
* Storing a local copy of preloads for concatenating
* new entries.
*/
private preloads;
/**
* Storing a local copy of metaFiles for concatenating
* new entries.
*/
private metaFiles;
/**
* Storing a local copy of commands for concatenating
* new entries.
*/
private commands;
/**
* Storing a local copy of providers for concatenating
* new entries.
*/
private providers;
/**
* Storing a local copy of aceProviders for concatenating
* new entries.
*/
private aceProviders;
/**
* Storing a local copy of testProviders for concatenating
* new entries.
*/
private testProviders;
constructor(basePath: string);
/**
* Handle `preloads` in a custom way on rollback, since the `mrm-core` uses
* `lodash.unset` which replaces the array index value with `null` and
* we instead want to remove the index value completely.
*/
onset(lifecycle: string, body: any): true | undefined;
/**
* Set the exception handler namespace.
*/
setExceptionHandler(namespace: string): this;
/**
* Set the preload file to the `.adonisrc.json` file.
*/
setPreload(filePath: string, environment?: AppEnvironments[], optional?: boolean): this;
/**
* Set IoC container aliases
*/
setAlias(namespace: string, autoloadPath: string): this;
/**
* Set custom directory
*/
setDirectory(key: string, value: string): this;
/**
* Add custom file to `metaFiles` array.
*/
addMetaFile(filePath: string, reloadServer?: boolean): void;
/**
* Add new commands to the commands array
*/
addCommand(commandPath: string): void;
/**
* Add new providers to the providers array
*/
addProvider(provider: string): void;
/**
* Add new providers to the ace providers array
*/
addAceProvider(provider: string): void;
/**
* Add new providers to the test providers array
*/
addTestProvider(provider: string): void;
}
+213
View File
@@ -0,0 +1,213 @@
"use strict";
/*
* @adonisjs/sink
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.AdonisRcFile = void 0;
const Json_1 = require("../Formats/Json");
/**
* Exposes API to mutate the contents of `.adonisrc.json` file.
*/
class AdonisRcFile extends Json_1.JsonFile {
constructor(basePath) {
super(basePath, '.adonisrc.json');
/**
* Storing a local copy of preloads for concatenating
* new entries.
*/
this.preloads = [];
/**
* Storing a local copy of metaFiles for concatenating
* new entries.
*/
this.metaFiles = [];
/**
* Storing a local copy of commands for concatenating
* new entries.
*/
this.commands = [];
/**
* Storing a local copy of providers for concatenating
* new entries.
*/
this.providers = [];
/**
* Storing a local copy of aceProviders for concatenating
* new entries.
*/
this.aceProviders = [];
/**
* Storing a local copy of testProviders for concatenating
* new entries.
*/
this.testProviders = [];
this.preloads = this.get('preloads', []);
this.metaFiles = this.get('metaFiles', []);
this.commands = this.get('commands', []);
this.providers = this.get('providers', []);
this.aceProviders = this.get('aceProviders', []);
this.testProviders = this.get('testProviders', []);
}
/**
* Handle `preloads` in a custom way on rollback, since the `mrm-core` uses
* `lodash.unset` which replaces the array index value with `null` and
* we instead want to remove the index value completely.
*/
onset(lifecycle, body) {
if (lifecycle === 'rollback') {
let key = null;
if (body.key.startsWith('preloads')) {
key = 'preloads';
}
if (body.key.startsWith('metaFiles')) {
key = 'metaFiles';
}
if (body.key.startsWith('commands')) {
key = 'commands';
}
if (body.key.startsWith('providers')) {
key = 'providers';
}
if (body.key.startsWith('aceProviders')) {
key = 'aceProviders';
}
if (body.key.startsWith('testProviders')) {
key = 'testProviders';
}
if (!key) {
return;
}
const index = body.key.split('[')[1].replace(/\]/g, '');
this.get(key, []).splice(index, 1);
return true;
}
}
/**
* Set the exception handler namespace.
*/
setExceptionHandler(namespace) {
this.set('exceptionHandlerNamespace', namespace);
return this;
}
/**
* Set the preload file to the `.adonisrc.json` file.
*/
setPreload(filePath, environment, optional) {
let preloadIndex = this.preloads.findIndex((preload) => {
if (preload.file) {
return preload.file === filePath;
}
return preload === filePath;
});
preloadIndex = preloadIndex === -1 ? this.preloads.length : preloadIndex;
let preloadEntry = {
file: filePath,
};
/**
* Set the environment when it exists
*/
if (environment && environment.length) {
preloadEntry.environment = environment;
}
/**
* Set the optional property when it exists
*/
if (optional !== undefined) {
preloadEntry.optional = optional;
}
/**
* Set preload entry as string, when it doesn't have explicit environment
* and optional fields.
*/
if (preloadEntry.optional === undefined && preloadEntry.environment === undefined) {
preloadEntry = preloadEntry.file;
}
this.preloads[preloadIndex] = preloadEntry;
this.set(`preloads[${preloadIndex}]`, preloadEntry);
return this;
}
/**
* Set IoC container aliases
*/
setAlias(namespace, autoloadPath) {
this.set(`aliases.${namespace}`, autoloadPath);
return this;
}
/**
* Set custom directory
*/
setDirectory(key, value) {
this.set(`directories.${key}`, value);
return this;
}
/**
* Add custom file to `metaFiles` array.
*/
addMetaFile(filePath, reloadServer) {
let entryIndex = this.metaFiles.findIndex((file) => {
if (file.pattern) {
return file.pattern === filePath;
}
return file === filePath;
});
entryIndex = entryIndex === -1 ? this.metaFiles.length : entryIndex;
const entry = reloadServer === false
? {
pattern: filePath,
reloadServer: false,
}
: filePath;
this.metaFiles[entryIndex] = entry;
this.set(`metaFiles[${entryIndex}]`, entry);
}
/**
* Add new commands to the commands array
*/
addCommand(commandPath) {
let entryIndex = this.commands.findIndex((command) => {
return command === commandPath;
});
entryIndex = entryIndex === -1 ? this.commands.length : entryIndex;
this.commands[entryIndex] = commandPath;
this.set(`commands[${entryIndex}]`, commandPath);
}
/**
* Add new providers to the providers array
*/
addProvider(provider) {
let entryIndex = this.providers.findIndex((command) => {
return command === provider;
});
entryIndex = entryIndex === -1 ? this.providers.length : entryIndex;
this.providers[entryIndex] = provider;
this.set(`providers[${entryIndex}]`, provider);
}
/**
* Add new providers to the ace providers array
*/
addAceProvider(provider) {
let entryIndex = this.aceProviders.findIndex((command) => {
return command === provider;
});
entryIndex = entryIndex === -1 ? this.aceProviders.length : entryIndex;
this.aceProviders[entryIndex] = provider;
this.set(`aceProviders[${entryIndex}]`, provider);
}
/**
* Add new providers to the test providers array
*/
addTestProvider(provider) {
let entryIndex = this.testProviders.findIndex((command) => {
return command === provider;
});
entryIndex = entryIndex === -1 ? this.testProviders.length : entryIndex;
this.testProviders[entryIndex] = provider;
this.set(`testProviders[${entryIndex}]`, provider);
}
}
exports.AdonisRcFile = AdonisRcFile;
+36
View File
@@ -0,0 +1,36 @@
/**
* Exposes the API to run mutations on `.env` file. The same variables
* will be added to `.env.example` with empty contents.
*/
export declare class EnvFile {
private basePath;
private envContents;
private exampleEnvContents;
constructor(basePath: string);
/**
* Set key/value pair inside the `.env` file
*/
set(key: string, value: any): this;
/**
* Returns a key/value pair of the file contents.
*/
get(): {
[key: string]: string;
};
/**
* Returns a boolean telling if the file exists.
*/
exists(): boolean;
/**
* Unset a key/value pair from the `.env` and `.env.example` file
*/
unset(key: string): this;
/**
* Commit mutations
*/
commit(): void;
/**
* Rollback mutations
*/
rollback(): void;
}
+84
View File
@@ -0,0 +1,84 @@
"use strict";
/*
* @adonisjs/sink
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.EnvFile = void 0;
const NewLine_1 = require("../Formats/NewLine");
/**
* Exposes the API to run mutations on `.env` file. The same variables
* will be added to `.env.example` with empty contents.
*/
class EnvFile {
constructor(basePath) {
this.basePath = basePath;
this.envContents = new NewLine_1.NewLineFile(this.basePath, '.env');
this.exampleEnvContents = new NewLine_1.NewLineFile(this.basePath, '.env.example');
}
/**
* Set key/value pair inside the `.env` file
*/
set(key, value) {
const matchingLine = this.envContents.get().find((line) => line.startsWith(`${key}=`));
const newText = `${key}=${value}`;
if (matchingLine && newText !== matchingLine) {
this.envContents.update(matchingLine, newText);
return this;
}
this.envContents.add(newText);
this.exampleEnvContents.add(newText);
return this;
}
/**
* Returns a key/value pair of the file contents.
*/
get() {
return this.envContents.get().reduce((result, line) => {
const [key, value] = line.split('=');
result[key.trim()] = value.trim();
return result;
}, {});
}
/**
* Returns a boolean telling if the file exists.
*/
exists() {
return this.envContents.exists();
}
/**
* Unset a key/value pair from the `.env` and `.env.example` file
*/
unset(key) {
const matchingLine = this.envContents.get().find((line) => line.startsWith(`${key}=`));
if (matchingLine) {
this.envContents.remove(matchingLine);
}
const exampleFileMatchingLine = this.exampleEnvContents.get().find((line) => {
return line.startsWith(`${key}=`);
});
if (exampleFileMatchingLine) {
this.exampleEnvContents.remove(exampleFileMatchingLine);
}
return this;
}
/**
* Commit mutations
*/
commit() {
this.envContents.commit();
this.exampleEnvContents.commit();
}
/**
* Rollback mutations
*/
rollback() {
this.envContents.rollback();
this.exampleEnvContents.rollback();
}
}
exports.EnvFile = EnvFile;
+187
View File
@@ -0,0 +1,187 @@
/// <reference types="node" />
/// <reference types="node" />
import { packageJson } from 'mrm-core';
import { SpawnSyncReturns, StdioOptions } from 'child_process';
import { File } from '../Base/File';
type InstallerNotifier = (list: string[], dev: boolean) => void;
type Dependencies = {
list: string[];
versions?: any;
dev: boolean;
};
type SupportedPackageManager = 'yarn' | 'pnpm' | 'npm';
/**
* Exposes the API to work with `package.json` file. The file is
* same as a standard JSON file, but with some special methods
* related to package file itself.
*/
export declare class PackageJsonFile extends File {
private installerOutput;
filePointer: ReturnType<typeof packageJson>;
/**
* Collection of actions to be executed on package file
*/
protected actions: never[];
/**
* A copy of install instructions
*/
protected packages: {
install: {
dependency: string;
version: string;
dev: boolean;
}[];
uninstall: {
dependency: string;
dev: boolean;
}[];
};
/**
* Explicitly force to use another client instead of npm
*/
private packageManager;
/**
* Method invoked before installing dependencies
*/
private beforeInstallHooks?;
/**
* Method invoked before uninstalling dependencies
*/
private beforeUninstallHooks?;
constructor(basePath: string, installerOutput?: StdioOptions);
/**
* Run hooks for action or uninstall action
*/
private runHooks;
/**
* Sets installation client
*/
private setClient;
/**
* Executes the installer `install` or `uninstall` action. Use
* `this.installerFnAsync` for async version
*/
private installerFn;
/**
* Executes the installer `install` or `uninstall` action. Use
* `this.installerFn` for sync version
*/
private installerFnAsync;
/**
* Install and uninstall packages defined via `this.install`
* and `this.uninstall`
*/
private commitDependencies;
/**
* Performing uninstalling as a rollback step. Which means, this method
* will remove packages marked for installation.
*/
private rollbackDependencies;
/**
* Same as `commitInstalls` but async
*/
private commitDependenciesAsync;
/**
* Same as `rollbackInstalls` but async.
*/
private rollbackDependenciesAsync;
/**
* Commits actions defined on the given file
*/
private commitActions;
/**
* Rollsback actions defined on the package file
*/
private rollbackActions;
/**
* Set key/value pair in the package.json file
*/
set(key: string, value: any): this;
/**
* Set a specific client to be used
*/
useClient(client: SupportedPackageManager): this;
/**
* Enable/disable use of yarn
* @deprecated The "yarn" method is deprecated. Please use "useClient('yarn')" instead.
*/
yarn(_useYarn: boolean): this;
/**
* Unset key/value pair from the package.json file
*/
unset(key: string): this;
/**
* Set package.json script
*/
setScript(name: string, script: string): this;
/**
* Append to existing package.json script
*/
appendScript(name: string, script: string): this;
/**
* Prepend to existing package.json script
*/
prependScript(name: string, script: string): this;
/**
* Remove existing script or remove a given action from an
* existing script
*/
removeScript(name: string, script?: string | RegExp): this;
/**
* Install dependencies
*/
install(dependency: string, version?: string, dev?: boolean): this;
/**
* Uninstall dependencies
*/
uninstall(dependency: string, dev?: boolean): this;
/**
* Remove file
*/
delete(): this;
/**
* Returns value for a given key from the file
*/
get(): any;
get(address: string | string[], defaultValue?: any): any;
/**
* A boolean telling if the file already exists
*/
exists(): boolean;
/**
* Returns a list of dependencies along with specific versions (if any)
*/
getInstalls(dev?: boolean): Dependencies;
/**
* Returns uninstalls list for prod or development
* dependencies.
*/
getUninstalls(dev: boolean): Dependencies;
/**
* Define a function to be called before installing dependencies
*/
beforeInstall(callback: InstallerNotifier): this;
/**
* Define a function to be called before uninstalling dependencies
*/
beforeUninstall(callback: InstallerNotifier): this;
/**
* Commit mutations
*/
commit(): SpawnSyncReturns<Buffer> | undefined;
/**
* Commits async. The files are still written using synchronous
* API. However, the install and uninstall becomes async.
*/
commitAsync(): Promise<SpawnSyncReturns<Buffer> | undefined>;
/**
* Rollback mutations
*/
rollback(): SpawnSyncReturns<Buffer> | undefined;
/**
* Rollsback async. The files are still written using synchronous
* API. However, the uninstall becomes async.
*/
rollbackAsync(): Promise<SpawnSyncReturns<Buffer> | undefined>;
}
export {};
+452
View File
@@ -0,0 +1,452 @@
"use strict";
/*
* @adonisjs/sink
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.PackageJsonFile = void 0;
const mrm_core_1 = require("mrm-core");
const child_process_1 = require("child_process");
const File_1 = require("../Base/File");
/**
* Exposes the API to work with `package.json` file. The file is
* same as a standard JSON file, but with some special methods
* related to package file itself.
*/
class PackageJsonFile extends File_1.File {
constructor(basePath, installerOutput = 'pipe') {
super(basePath);
this.installerOutput = installerOutput;
/**
* Collection of actions to be executed on package file
*/
this.actions = [];
/**
* A copy of install instructions
*/
this.packages = {
install: [],
uninstall: [],
};
this.cdIn();
this.filePointer = (0, mrm_core_1.packageJson)();
this.cdOut();
}
/**
* Run hooks for action or uninstall action
*/
runHooks(action, list, dev) {
if (action === 'install' && typeof this.beforeInstallHooks === 'function') {
this.beforeInstallHooks(list, dev);
}
else if (action === 'uninstall' && typeof this.beforeUninstallHooks === 'function') {
this.beforeUninstallHooks(list, dev);
}
}
/**
* Sets installation client
*/
setClient(options) {
if (this.packageManager === 'yarn') {
options.yarn = true;
}
else if (this.packageManager === 'pnpm') {
options.pnpm = true;
}
}
/**
* Executes the installer `install` or `uninstall` action. Use
* `this.installerFnAsync` for async version
*/
installerFn(action, list, options) {
if (!list.length) {
return;
}
this.setClient(options);
this.runHooks(action, list, options.dev);
const fn = action === 'install' ? mrm_core_1.install : mrm_core_1.uninstall;
return fn(list, options, (command, args) => {
return (0, child_process_1.spawnSync)(command, args, { stdio: this.installerOutput });
});
}
/**
* Executes the installer `install` or `uninstall` action. Use
* `this.installerFn` for sync version
*/
installerFnAsync(action, list, options) {
return new Promise((resolve) => {
if (!list.length) {
resolve(undefined);
return;
}
this.setClient(options);
this.runHooks(action, list, options.dev);
let response;
const fn = action === 'install' ? mrm_core_1.install : mrm_core_1.uninstall;
let callbackInvoked = false;
fn(list, options, (command, args) => {
callbackInvoked = true;
const runner = (0, child_process_1.spawn)(command, args, { stdio: 'pipe' });
response = {
pid: runner.pid,
output: [],
stdout: Buffer.from(''),
stderr: Buffer.from(''),
status: null,
signal: null,
};
runner.stdout.on('data', (chunk) => {
response.stdout = Buffer.concat([response.stdout, chunk]);
});
runner.stderr.on('data', (chunk) => {
response.stderr = Buffer.concat([response.stderr, chunk]);
});
runner.on('close', (code, signal) => {
response.status = code;
response.signal = signal;
resolve(response);
});
});
if (!callbackInvoked) {
resolve(undefined);
}
});
}
/**
* Install and uninstall packages defined via `this.install`
* and `this.uninstall`
*/
commitDependencies(installs, uninstalls) {
let response;
for (let { list, versions, dev } of installs) {
response = this.installerFn('install', list, { versions, dev });
if (response && response.status === 1) {
return response;
}
}
for (let { list, dev } of uninstalls) {
response = this.installerFn('uninstall', list, { dev });
if (response && response.status === 1) {
return response;
}
}
}
/**
* Performing uninstalling as a rollback step. Which means, this method
* will remove packages marked for installation.
*/
rollbackDependencies(installs) {
let response;
for (let { list, dev } of installs) {
response = this.installerFn('uninstall', list, { dev });
if (response && response.status === 1) {
return response;
}
}
}
/**
* Same as `commitInstalls` but async
*/
async commitDependenciesAsync(installs, uninstalls) {
let response;
for (let { list, versions, dev } of installs) {
response = await this.installerFnAsync('install', list, { versions, dev });
if (response && response.status === 1) {
return response;
}
}
for (let { list, dev } of uninstalls) {
response = await this.installerFnAsync('uninstall', list, { dev });
if (response && response.status === 1) {
return response;
}
}
}
/**
* Same as `rollbackInstalls` but async.
*/
async rollbackDependenciesAsync(installs) {
let response;
for (let { list, dev } of installs) {
response = await this.installerFnAsync('uninstall', list, { dev });
if (response && response.status === 1) {
return response;
}
}
}
/**
* Commits actions defined on the given file
*/
commitActions() {
const actions = this.getCommitActions();
const deleteFile = actions.find(({ action }) => action === 'delete');
/**
* In case of `delete` action. There is no point running
* other actions and we can simply delete the file
*/
if (deleteFile) {
this.filePointer.delete();
this.cdOut();
return false;
}
/**
* Executing all actions
*/
actions.forEach(({ action, body }) => {
if (['set', 'unset'].indexOf(action) > -1) {
this.filePointer[action](body.key, body.value);
return;
}
if (['prependScript', 'appendScript', 'setScript', 'removeScript'].indexOf(action) > -1) {
this.filePointer[action](body.name, body.script);
return;
}
});
/**
* Save the file to the disk before starting install process.
*/
this.filePointer.save();
return true;
}
/**
* Rollsback actions defined on the package file
*/
rollbackActions() {
const actions = this.getCommitActions();
/**
* Executing actions in reverse.
*/
actions.forEach(({ action, body }) => {
if (action === 'set') {
this.filePointer.unset(body.key);
return;
}
if (action === 'setScript') {
this.filePointer.removeScript(body.name);
return;
}
if (['prependScript', 'appendScript'].indexOf(action) > -1) {
this.filePointer.removeScript(body.name, new RegExp(body.script));
return;
}
});
/**
* Write file to the disk
*/
this.filePointer.save();
return true;
}
/**
* Set key/value pair in the package.json file
*/
set(key, value) {
this.addAction('set', { key, value });
return this;
}
/**
* Set a specific client to be used
*/
useClient(client) {
this.packageManager = client;
return this;
}
/**
* Enable/disable use of yarn
* @deprecated The "yarn" method is deprecated. Please use "useClient('yarn')" instead.
*/
yarn(_useYarn) {
this.packageManager = 'yarn';
return this;
}
/**
* Unset key/value pair from the package.json file
*/
unset(key) {
this.addAction('unset', { key });
return this;
}
/**
* Set package.json script
*/
setScript(name, script) {
this.addAction('setScript', { name, script });
return this;
}
/**
* Append to existing package.json script
*/
appendScript(name, script) {
this.addAction('appendScript', { name, script });
return this;
}
/**
* Prepend to existing package.json script
*/
prependScript(name, script) {
this.addAction('prependScript', { name, script });
return this;
}
/**
* Remove existing script or remove a given action from an
* existing script
*/
removeScript(name, script) {
this.addAction('removeScript', { name, script });
return this;
}
/**
* Install dependencies
*/
install(dependency, version = 'latest', dev = true) {
this.packages.install.push({ dependency, version, dev });
return this;
}
/**
* Uninstall dependencies
*/
uninstall(dependency, dev = true) {
this.packages.uninstall.push({ dependency, dev });
return this;
}
/**
* Remove file
*/
delete() {
this.addAction('delete');
return this;
}
get(address, defaultValue) {
return address ? this.filePointer.get(address, defaultValue) : this.filePointer.get();
}
/**
* A boolean telling if the file already exists
*/
exists() {
return this.filePointer.exists();
}
/**
* Returns a list of dependencies along with specific versions (if any)
*/
getInstalls(dev = true) {
const dependencies = { versions: {}, list: [], dev };
return this.packages.install.reduce((result, dependency) => {
if (dependency.dev && dev) {
result.list.push(dependency.dependency);
if (dependency.version !== 'latest') {
result.versions[dependency.dependency] = dependency.version;
}
}
else if (!dependency.dev && !dev) {
result.list.push(dependency.dependency);
if (dependency.version !== 'latest') {
result.versions[dependency.dependency] = dependency.version;
}
}
return result;
}, dependencies);
}
/**
* Returns uninstalls list for prod or development
* dependencies.
*/
getUninstalls(dev) {
const dependencies = { list: [], dev };
return this.packages.uninstall.reduce((result, dependency) => {
if (dependency.dev && dev) {
result.list.push(dependency.dependency);
}
else if (!dependency.dev && !dev) {
result.list.push(dependency.dependency);
}
return result;
}, dependencies);
}
/**
* Define a function to be called before installing dependencies
*/
beforeInstall(callback) {
this.beforeInstallHooks = callback;
return this;
}
/**
* Define a function to be called before uninstalling dependencies
*/
beforeUninstall(callback) {
this.beforeUninstallHooks = callback;
return this;
}
/**
* Commit mutations
*/
commit() {
this.cdIn();
const success = this.commitActions();
if (!success) {
return;
}
/**
* Install/uninstall dependencies
*/
const response = this.commitDependencies([this.getInstalls(true), this.getInstalls(false)], [this.getUninstalls(true), this.getUninstalls(false)]);
this.cdOut();
return response;
}
/**
* Commits async. The files are still written using synchronous
* API. However, the install and uninstall becomes async.
*/
async commitAsync() {
this.cdIn();
const success = this.commitActions();
if (!success) {
return;
}
/**
* Install/uninstall dependencies
*/
const response = await this.commitDependenciesAsync([this.getInstalls(true), this.getInstalls(false)], [this.getUninstalls(true), this.getUninstalls(false)]);
this.cdOut();
return response;
}
/**
* Rollback mutations
*/
rollback() {
this.cdIn();
const success = this.rollbackActions();
if (!success) {
return;
}
/**
* Uninstalling installed packages
*/
const response = this.rollbackDependencies([this.getInstalls(true), this.getInstalls(false)]);
this.cdOut();
return response;
}
/**
* Rollsback async. The files are still written using synchronous
* API. However, the uninstall becomes async.
*/
async rollbackAsync() {
this.cdIn();
const success = this.rollbackActions();
if (!success) {
return;
}
/**
* Uninstalling installed packages
*/
const response = await this.rollbackDependenciesAsync([
this.getInstalls(true),
this.getInstalls(false),
]);
this.cdOut();
return response;
}
}
exports.PackageJsonFile = PackageJsonFile;
+11
View File
@@ -0,0 +1,11 @@
export { File } from './Base/File';
export { KeyValuePair } from './Base/KeyValuePair';
export { IniFile } from './Formats/Ini';
export { JsonFile } from './Formats/Json';
export { MustacheFile } from './Formats/Mustache';
export { NewLineFile } from './Formats/NewLine';
export { TemplateLiteralFile } from './Formats/TemplateLiteral';
export { YamlFile } from './Formats/Yaml';
export { AdonisRcFile } from './Special/AdonisRc';
export { EnvFile } from './Special/Env';
export { PackageJsonFile } from './Special/PackageJson';
+33
View File
@@ -0,0 +1,33 @@
"use strict";
/*
* @adonisjs/files
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.PackageJsonFile = exports.EnvFile = exports.AdonisRcFile = exports.YamlFile = exports.TemplateLiteralFile = exports.NewLineFile = exports.MustacheFile = exports.JsonFile = exports.IniFile = exports.KeyValuePair = exports.File = void 0;
var File_1 = require("./Base/File");
Object.defineProperty(exports, "File", { enumerable: true, get: function () { return File_1.File; } });
var KeyValuePair_1 = require("./Base/KeyValuePair");
Object.defineProperty(exports, "KeyValuePair", { enumerable: true, get: function () { return KeyValuePair_1.KeyValuePair; } });
var Ini_1 = require("./Formats/Ini");
Object.defineProperty(exports, "IniFile", { enumerable: true, get: function () { return Ini_1.IniFile; } });
var Json_1 = require("./Formats/Json");
Object.defineProperty(exports, "JsonFile", { enumerable: true, get: function () { return Json_1.JsonFile; } });
var Mustache_1 = require("./Formats/Mustache");
Object.defineProperty(exports, "MustacheFile", { enumerable: true, get: function () { return Mustache_1.MustacheFile; } });
var NewLine_1 = require("./Formats/NewLine");
Object.defineProperty(exports, "NewLineFile", { enumerable: true, get: function () { return NewLine_1.NewLineFile; } });
var TemplateLiteral_1 = require("./Formats/TemplateLiteral");
Object.defineProperty(exports, "TemplateLiteralFile", { enumerable: true, get: function () { return TemplateLiteral_1.TemplateLiteralFile; } });
var Yaml_1 = require("./Formats/Yaml");
Object.defineProperty(exports, "YamlFile", { enumerable: true, get: function () { return Yaml_1.YamlFile; } });
var AdonisRc_1 = require("./Special/AdonisRc");
Object.defineProperty(exports, "AdonisRcFile", { enumerable: true, get: function () { return AdonisRc_1.AdonisRcFile; } });
var Env_1 = require("./Special/Env");
Object.defineProperty(exports, "EnvFile", { enumerable: true, get: function () { return Env_1.EnvFile; } });
var PackageJson_1 = require("./Special/PackageJson");
Object.defineProperty(exports, "PackageJsonFile", { enumerable: true, get: function () { return PackageJson_1.PackageJsonFile; } });
+91
View File
@@ -0,0 +1,91 @@
import { ApplicationContract } from '@ioc:Adonis/Core/Application';
import * as sink from '../../../index';
/**
* Exposes the API to execute the instructions of a package, defined inside
* the `package.json` file.
*/
export declare class Instructions {
private packageName;
private projectRoot;
private application;
private verbose;
/**
* Path to the package package.json file
*/
private packagePath;
private markdownDisplay;
private logger;
constructor(packageName: string, projectRoot: string, application: ApplicationContract, verbose?: boolean);
/**
* Formats object to string
*/
private formatObject;
/**
* Formats array to string
*/
private formatArray;
/**
* Returns the suffix for the logger statements
*/
private getSuffix;
/**
* Returns the absolute path to the package
*/
private getPackagePath;
/**
* Load package json file from the package root directory
*/
private loadPackageJsonFile;
/**
* Copies templates to the user project
*/
private copyTemplates;
/**
* Set environment variables
*/
private setEnvVariables;
/**
* Adds the types to the tsconfig.json file
*/
private setTypes;
/**
* Adds the meta files to `.adonisrc.json` file
*/
private setMetaFiles;
/**
* Adds the preloads to `.adonisrc.json` file
*/
private setPreloads;
/**
* Set commands inside the adonisrc.json file
*/
private setCommands;
/**
* Set aliases inside the adonisrc.json file
*/
private setAliases;
/**
* Sets providers or ace providers inside the `.adonisrc.json` file
*/
private setProviders;
/**
* Executes the instructions fn exposed by the package inside package.json file.
*/
private runInstructions;
/**
* Renders the markdown file if defined inside the package.json file.
*/
private renderMarkdownFile;
/**
* Preset markdown display for avoiding prompt
*/
setDisplay(display: 'browser' | 'terminal'): this;
/**
* Define a custom logger to use
*/
useLogger(logger: typeof sink.logger): this;
/**
* Execute the instructions file
*/
execute(): Promise<boolean>;
}
+350
View File
@@ -0,0 +1,350 @@
"use strict";
/*
* @adonisjs/sink
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Instructions = void 0;
const path_1 = require("path");
const utils_1 = require("@poppinss/utils");
const helpers_1 = require("@poppinss/utils/build/helpers");
const sink = __importStar(require("../../../index"));
const TemplatesManager_1 = require("../TemplatesManager");
/**
* Exposes the API to execute the instructions of a package, defined inside
* the `package.json` file.
*/
class Instructions {
constructor(packageName, projectRoot, application, verbose = false) {
this.packageName = packageName;
this.projectRoot = projectRoot;
this.application = application;
this.verbose = verbose;
/**
* Path to the package package.json file
*/
this.packagePath = this.getPackagePath();
this.markdownDisplay = undefined;
this.logger = sink.logger;
}
/**
* Formats object to string
*/
formatObject(values) {
return Object.keys(values)
.map((key) => {
return `"${key} = ${values[key]}"`;
})
.join(',');
}
/**
* Formats array to string
*/
formatArray(values) {
return values.map((v) => `"${v}"`).join(',');
}
/**
* Returns the suffix for the logger statements
*/
getSuffix(value, key) {
if (!this.verbose) {
return '';
}
if (key) {
return this.logger.colors.yellow().dim(`{ ${key} += ${value} }`);
}
return this.logger.colors.yellow().dim(`{ ${value} }`);
}
/**
* Returns the absolute path to the package
*/
getPackagePath() {
try {
return (0, helpers_1.resolveFrom)(this.projectRoot, `${this.packageName}/package.json`);
}
catch (error) {
if (['MODULE_NOT_FOUND', 'ENOENT'].includes(error.code)) {
throw new Error(`Cannot invoke instructions. Missing package "${this.packageName}"`);
}
throw error;
}
}
/**
* Load package json file from the package root directory
*/
loadPackageJsonFile() {
return require(this.packagePath);
}
/**
* Copies templates to the user project
*/
copyTemplates(instructions) {
if (!instructions.templates) {
return;
}
const templatesSourceDir = instructions.templates.basePath || './build/templates';
const templatesManager = new TemplatesManager_1.TemplatesManager(this.projectRoot, (0, path_1.join)((0, path_1.dirname)(this.packagePath), templatesSourceDir), this.application);
templatesManager.useLogger(this.logger).copy(instructions.templates);
}
/**
* Set environment variables
*/
setEnvVariables(instructions) {
if (!instructions.env) {
return;
}
const envFile = new sink.files.EnvFile(this.projectRoot);
Object.keys(instructions.env).forEach((envKey) => envFile.set(envKey, instructions.env[envKey]));
envFile.commit();
const suffix = this.getSuffix(this.formatObject(instructions.env));
this.logger.action('update').succeeded(`.env ${suffix}`);
}
/**
* Adds the types to the tsconfig.json file
*/
setTypes(instructions) {
if (!instructions.types) {
return;
}
const fileName = 'tsconfig.json';
const tsConfig = new sink.files.JsonFile(this.projectRoot, fileName);
const existingTypes = tsConfig.get('compilerOptions.types') || [];
/**
* Push type when doesn't exists already
*/
if (!existingTypes.find((type) => type.includes(instructions.types))) {
existingTypes.push(instructions.types);
tsConfig.set('compilerOptions.types', existingTypes);
tsConfig.commit();
const suffix = this.getSuffix(this.formatArray([instructions.types]), 'types');
this.logger.action('update').succeeded(`${fileName} ${suffix}`);
}
}
/**
* Adds the meta files to `.adonisrc.json` file
*/
setMetaFiles(instructions) {
if (!instructions.metaFiles) {
return;
}
const adonisRcFile = new sink.files.AdonisRcFile(this.projectRoot);
instructions.metaFiles.forEach((metaFile) => {
if (typeof metaFile === 'string') {
adonisRcFile.addMetaFile(metaFile);
}
else {
adonisRcFile.addMetaFile(metaFile.pattern, metaFile.reloadServer);
}
});
adonisRcFile.commit();
const suffix = this.getSuffix(this.formatArray(instructions.metaFiles.map((metaFile) => {
return typeof metaFile === 'string' ? metaFile : metaFile.pattern;
})), 'metaFiles');
this.logger.action('update').succeeded(`.adonisrc.json ${suffix}`);
}
/**
* Adds the preloads to `.adonisrc.json` file
*/
setPreloads(instructions) {
if (!instructions.preloads) {
return;
}
const adonisRcFile = new sink.files.AdonisRcFile(this.projectRoot);
instructions.preloads.forEach((preloadFile) => {
if (typeof preloadFile === 'string') {
adonisRcFile.setPreload(preloadFile);
}
else {
adonisRcFile.setPreload(preloadFile.file, preloadFile.environment, preloadFile.optional);
}
});
adonisRcFile.commit();
const suffix = this.getSuffix(this.formatArray(instructions.preloads.map((preloadFile) => {
return typeof preloadFile === 'string' ? preloadFile : preloadFile.file;
})), 'preloads');
this.logger.action('update').succeeded(`.adonisrc.json ${suffix}`);
}
/**
* Set commands inside the adonisrc.json file
*/
setCommands(instructions) {
if (!instructions.commands) {
return;
}
const adonisRcFile = new sink.files.AdonisRcFile(this.projectRoot);
instructions.commands.forEach((command) => adonisRcFile.addCommand(command));
adonisRcFile.commit();
const suffix = this.getSuffix(this.formatArray(instructions.commands), 'commands');
this.logger.action('update').succeeded(`.adonisrc.json ${suffix}`);
}
/**
* Set aliases inside the adonisrc.json file
*/
setAliases(instructions) {
if (!instructions.aliases) {
return;
}
const adonisRcFile = new sink.files.AdonisRcFile(this.projectRoot);
const tsConfig = new sink.files.JsonFile(this.projectRoot, 'tsconfig.json');
const existingPaths = tsConfig.get('compilerOptions.paths') || {};
Object.keys(instructions.aliases).forEach((alias) => {
adonisRcFile.setAlias(alias, instructions.aliases[alias]);
existingPaths[`${alias}/*`] = [`${instructions.aliases[alias]}/*`];
});
const suffix = this.getSuffix(this.formatObject(instructions.aliases), 'aliases');
adonisRcFile.commit();
this.logger.action('update').succeeded(`.adonisrc.json ${suffix}`);
tsConfig.set('compilerOptions.paths', existingPaths);
tsConfig.commit();
this.logger.action('update').succeeded(`tsconfig.json ${suffix}`);
}
/**
* Sets providers or ace providers inside the `.adonisrc.json` file
*/
setProviders(instructions) {
/**
* Return early when not providers are mentioned
*/
if (!instructions.providers && !instructions.aceProviders && !instructions.testProviders) {
return;
}
const adonisRcFile = new sink.files.AdonisRcFile(this.projectRoot);
if (instructions.providers) {
instructions.providers.forEach((provider) => adonisRcFile.addProvider(provider));
}
if (instructions.aceProviders) {
instructions.aceProviders.forEach((provider) => adonisRcFile.addAceProvider(provider));
}
if (instructions.testProviders) {
instructions.testProviders.forEach((provider) => adonisRcFile.addTestProvider(provider));
}
adonisRcFile.commit();
if (instructions.providers) {
const suffix = this.getSuffix(this.formatArray(instructions.providers), 'providers');
this.logger.action('update').succeeded(`.adonisrc.json ${suffix}`);
}
if (instructions.aceProviders) {
const suffix = this.getSuffix(this.formatArray(instructions.aceProviders), 'aceProviders');
this.logger.action('update').succeeded(`.adonisrc.json ${suffix}`);
}
if (instructions.testProviders) {
const suffix = this.getSuffix(this.formatArray(instructions.testProviders), 'testProviders');
this.logger.action('update').succeeded(`.adonisrc.json ${suffix}`);
}
}
/**
* Executes the instructions fn exposed by the package inside package.json file.
*/
async runInstructions(instructions) {
if (!instructions.instructions) {
return;
}
/**
* Path to the instructions file is resolved from the package root.
*/
const instructionsPath = (0, helpers_1.resolveFrom)((0, path_1.dirname)(this.packagePath), instructions.instructions);
/**
* Requiring and executing instructions file
*/
const instructionsFn = (0, utils_1.esmRequire)(instructionsPath);
await instructionsFn(this.projectRoot, this.application, {
...sink,
logger: this.logger,
});
}
/**
* Renders the markdown file if defined inside the package.json file.
*/
async renderMarkdownFile(instructions) {
if (!instructions.instructionsMd || !this.verbose) {
return;
}
if (!this.markdownDisplay) {
this.logger.info('The package wants to display readable instructions for the setup');
this.markdownDisplay = await sink.getPrompt().choice('Select where to display instructions', [
{
name: 'browser',
message: 'In the browser',
},
{
name: 'terminal',
message: 'In the terminal',
},
]);
}
/**
* Render markdown file when `instructionsMd` property is defined in
* package.json file
*/
const renderer = new sink.tasks.MarkdownRenderer((0, path_1.join)((0, path_1.dirname)(this.packagePath), instructions.instructionsMd), this.packageName);
if (this.markdownDisplay === 'browser') {
renderer.renderInBrowser();
}
else {
console.log('');
renderer.renderInTerminal();
}
}
/**
* Preset markdown display for avoiding prompt
*/
setDisplay(display) {
this.markdownDisplay = display;
return this;
}
/**
* Define a custom logger to use
*/
useLogger(logger) {
this.logger = logger;
return this;
}
/**
* Execute the instructions file
*/
async execute() {
const pkg = this.loadPackageJsonFile();
if (!pkg.adonisjs) {
return true;
}
await this.runInstructions(pkg.adonisjs);
this.copyTemplates(pkg.adonisjs);
this.setEnvVariables(pkg.adonisjs);
this.setTypes(pkg.adonisjs);
this.setCommands(pkg.adonisjs);
this.setAliases(pkg.adonisjs);
this.setProviders(pkg.adonisjs);
this.setMetaFiles(pkg.adonisjs);
this.setPreloads(pkg.adonisjs);
await this.renderMarkdownFile(pkg.adonisjs);
return true;
}
}
exports.Instructions = Instructions;
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,26 @@
/**
* Markdown renderer for opening the instructions md file inside the
* terminal or the browser.
*/
export declare class MarkdownRenderer {
private mdFileAbsPath;
private packageName;
constructor(mdFileAbsPath: string, packageName: string);
/**
* Generates HTML with the markdown processed code
*/
private generateHtml;
/**
* Opens the html contents by writing it to a temporary
* file and opens up the file inside the browser.
*/
private openContentsInBrowser;
/**
* Converts markdown to HTML and opens it up inside the browser
*/
renderInBrowser(): Promise<void>;
/**
* Writes markdown in the terminal
*/
renderInTerminal(): Promise<void>;
}
+83
View File
@@ -0,0 +1,83 @@
"use strict";
/*
* @adonisjs/sink
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.MarkdownRenderer = void 0;
const open_1 = __importDefault(require("open"));
const path_1 = require("path");
const os_1 = require("os");
const fs_extra_1 = require("fs-extra");
const Styles_1 = require("./Styles");
/**
* Markdown renderer for opening the instructions md file inside the
* terminal or the browser.
*/
class MarkdownRenderer {
constructor(mdFileAbsPath, packageName) {
this.mdFileAbsPath = mdFileAbsPath;
this.packageName = packageName;
}
/**
* Generates HTML with the markdown processed code
*/
generateHtml(contents) {
return `<html>
<head>
<style type="text/css">${Styles_1.css}</style>
</head>
<body>
<article class="markdown-body">
<h1> Setup instructions for
<a href="https://npmjs.org/package/${this.packageName}" target="_blank">${this.packageName}</a>
</h1>
${contents}
</article>
</body>
</html>`;
}
/**
* Opens the html contents by writing it to a temporary
* file and opens up the file inside the browser.
*/
async openContentsInBrowser(html) {
const filePath = (0, path_1.join)((0, os_1.tmpdir)(), `adonis-${new Date().getTime()}.html`);
await (0, fs_extra_1.outputFile)(filePath, html);
await (0, open_1.default)(filePath, { wait: false });
}
/**
* Converts markdown to HTML and opens it up inside the browser
*/
async renderInBrowser() {
const { marked, Renderer } = await import('marked');
const renderer = new Renderer();
try {
const contents = await (0, fs_extra_1.readFile)(this.mdFileAbsPath, 'utf-8');
const html = this.generateHtml(marked.setOptions({ renderer })(contents.trim()));
await this.openContentsInBrowser(html);
}
catch (error) { }
}
/**
* Writes markdown in the terminal
*/
async renderInTerminal() {
const { marked } = await import('marked');
const { default: TerminalRenderer } = await import('marked-terminal');
const renderer = new TerminalRenderer();
try {
const contents = await (0, fs_extra_1.readFile)(this.mdFileAbsPath, 'utf-8');
console.log(marked.setOptions({ renderer })(contents.trim()).trim());
}
catch (error) { }
}
}
exports.MarkdownRenderer = MarkdownRenderer;
@@ -0,0 +1,40 @@
import { ApplicationContract } from '@ioc:Adonis/Core/Application';
import * as sink from '../../../index';
import { TemplateNode } from '../../Contracts';
/**
* Templates manager to copy one or more templates to the user project.
*/
export declare class TemplatesManager {
private projectRoot;
private templatesSourceDir;
private application;
private logger;
constructor(projectRoot: string, templatesSourceDir: string, application: ApplicationContract);
/**
* Normalizes the template node to its object version
*/
private normalizeTemplateNode;
/**
* Returns directory for the template key. It is defined inside the adonisrc file.
*/
private getDirectoryFor;
/**
* Copy templates for a given pre-defined directory within the rcfile.
*/
private copyTemplateFor;
/**
* Copy one or more templates for a given pre-defined directory within the rc file.
*/
private copyTemplatesFor;
/**
* Define a custom logger to use
*/
useLogger(logger: typeof sink.logger): this;
/**
* Copy multiple templates to the destination. It takes the input of templates
* defined inside the package.json file.
*/
copy(templates: {
[key: string]: TemplateNode | TemplateNode[];
}): Promise<void>;
}
+143
View File
@@ -0,0 +1,143 @@
"use strict";
/*
* @adonisjs/sink
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TemplatesManager = void 0;
const path_1 = require("path");
const sink = __importStar(require("../../../index"));
const Mustache_1 = require("../../Files/Formats/Mustache");
const TemplateLiteral_1 = require("../../Files/Formats/TemplateLiteral");
/**
* Templates manager to copy one or more templates to the user project.
*/
class TemplatesManager {
constructor(projectRoot, templatesSourceDir, application) {
this.projectRoot = projectRoot;
this.templatesSourceDir = templatesSourceDir;
this.application = application;
this.logger = sink.logger;
if (!(0, path_1.isAbsolute)(this.projectRoot)) {
throw new Error('Templates manager needs an absolute path to the project root');
}
if (!(0, path_1.isAbsolute)(this.templatesSourceDir)) {
throw new Error('Templates manager needs an absolute path to the templates source directory');
}
}
/**
* Normalizes the template node to its object version
*/
normalizeTemplateNode(template) {
template =
typeof template === 'string'
? {
src: template,
dest: template.replace(new RegExp(`${(0, path_1.extname)(template)}$`), ''),
mustache: false,
data: {},
}
: template;
template.dest = (0, path_1.extname)(template.dest) === '' ? `${template.dest}.ts` : template.dest;
return template;
}
/**
* Returns directory for the template key. It is defined inside the adonisrc file.
*/
getDirectoryFor(templateFor) {
if (templateFor === './' || templateFor === '/') {
return './';
}
/**
* Ensure the object key inside package.json file is a known directory
*/
const configuredDirectory = this.application.directoriesMap.get(templateFor);
if (!configuredDirectory) {
this.logger.warning(`Unknown directory type ${this.logger.colors.underline(templateFor)}`);
return;
}
return configuredDirectory;
}
/**
* Copy templates for a given pre-defined directory within the rcfile.
*/
copyTemplateFor(templateFor, template) {
const configuredDirectory = this.getDirectoryFor(templateFor);
if (!configuredDirectory) {
return;
}
if (!template.src || !template.dest) {
throw new Error('"src" and "dest" are required when copying templates');
}
const sourcePath = (0, path_1.join)(this.templatesSourceDir, template.src);
const destinationPath = (0, path_1.normalize)(`${configuredDirectory}/${template.dest}`);
const renderer = template.mustache
? new Mustache_1.MustacheFile(this.projectRoot, destinationPath, sourcePath)
: new TemplateLiteral_1.TemplateLiteralFile(this.projectRoot, destinationPath, sourcePath);
const hasFile = renderer.exists();
renderer.apply(template.data);
renderer.commit();
if (hasFile) {
this.logger.action('create').skipped(destinationPath);
}
else {
this.logger.action('create').succeeded(destinationPath);
}
}
/**
* Copy one or more templates for a given pre-defined directory within the rc file.
*/
copyTemplatesFor(templateFor, templates) {
templates = Array.isArray(templates) ? templates : [templates];
templates
.map((template) => this.normalizeTemplateNode(template))
.forEach((template) => this.copyTemplateFor(templateFor, template));
}
/**
* Define a custom logger to use
*/
useLogger(logger) {
this.logger = logger;
return this;
}
/**
* Copy multiple templates to the destination. It takes the input of templates
* defined inside the package.json file.
*/
async copy(templates) {
Object.keys(templates).forEach((templateFor) => {
if (templateFor === 'basePath') {
return;
}
this.copyTemplatesFor(templateFor, templates[templateFor]);
});
}
}
exports.TemplatesManager = TemplatesManager;
+3
View File
@@ -0,0 +1,3 @@
export { Instructions } from './Instructions';
export { MarkdownRenderer } from './MarkdownRenderer';
export { TemplatesManager } from './TemplatesManager';
+17
View File
@@ -0,0 +1,17 @@
"use strict";
/*
* @adonisjs/sink
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.TemplatesManager = exports.MarkdownRenderer = exports.Instructions = void 0;
var Instructions_1 = require("./Instructions");
Object.defineProperty(exports, "Instructions", { enumerable: true, get: function () { return Instructions_1.Instructions; } });
var MarkdownRenderer_1 = require("./MarkdownRenderer");
Object.defineProperty(exports, "MarkdownRenderer", { enumerable: true, get: function () { return MarkdownRenderer_1.MarkdownRenderer; } });
var TemplatesManager_1 = require("./TemplatesManager");
Object.defineProperty(exports, "TemplatesManager", { enumerable: true, get: function () { return TemplatesManager_1.TemplatesManager; } });
+9
View File
@@ -0,0 +1,9 @@
/**
* Utility method to copy files
*/
export declare function copyFiles(sourceBaseDir: string, destinationBaseDir: string, files: string[], options?: {
overwrite: boolean;
}): {
filePath: string;
state: 'skipped' | 'copied';
}[];
+37
View File
@@ -0,0 +1,37 @@
"use strict";
/*
* @adonisjs/sink
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.copyFiles = void 0;
const path_1 = require("path");
const cp_file_1 = __importDefault(require("cp-file"));
const fs_1 = require("fs");
/**
* Utility method to copy files
*/
function copyFiles(sourceBaseDir, destinationBaseDir, files, options) {
const overwrite = options ? options.overwrite : false;
return files.map((file) => {
const absPath = (0, path_1.join)(sourceBaseDir, file);
if (!(0, fs_1.existsSync)(absPath)) {
throw new Error(`Missing source file "${absPath}"`);
}
const targetAbsPath = (0, path_1.join)(destinationBaseDir, file);
const hasTarget = (0, fs_1.existsSync)(targetAbsPath);
if (hasTarget && !overwrite) {
return { filePath: file, state: 'skipped' };
}
cp_file_1.default.sync(absPath, targetAbsPath, { overwrite: true });
return { filePath: file, state: 'copied' };
});
}
exports.copyFiles = copyFiles;
+7
View File
@@ -0,0 +1,7 @@
/**
* Returns the package manager in use by checking for the lock files
* on the disk or by inspecting the "npm_config_user_agent".
*
* Defaults to npm when unable to detect the package manager.
*/
export declare function getPackageManager(appRoot: string): 'yarn' | 'pnpm' | 'npm';
+37
View File
@@ -0,0 +1,37 @@
"use strict";
/*
* @adonisjs/sink
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.getPackageManager = void 0;
const path_1 = require("path");
const fs_extra_1 = require("fs-extra");
/**
* Returns the package manager in use by checking for the lock files
* on the disk or by inspecting the "npm_config_user_agent".
*
* Defaults to npm when unable to detect the package manager.
*/
function getPackageManager(appRoot) {
if ((0, fs_extra_1.pathExistsSync)((0, path_1.resolve)(appRoot, 'yarn.lock'))) {
return 'yarn';
}
if ((0, fs_extra_1.pathExistsSync)((0, path_1.resolve)(appRoot, 'pnpm-lock.yaml'))) {
return 'pnpm';
}
if (process.env.npm_config_user_agent) {
if (process.env.npm_config_user_agent.includes('yarn')) {
return 'yarn';
}
if (process.env.npm_config_user_agent.includes('pnpm')) {
return 'pnpm';
}
}
return 'npm';
}
exports.getPackageManager = getPackageManager;
+3
View File
@@ -0,0 +1,3 @@
export { isEmptyDir } from './isEmptyDir';
export { copyFiles } from './copyFiles';
export { getPackageManager } from './getPackageManager';
+17
View File
@@ -0,0 +1,17 @@
"use strict";
/*
* @adonisjs/sink
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.getPackageManager = exports.copyFiles = exports.isEmptyDir = void 0;
var isEmptyDir_1 = require("./isEmptyDir");
Object.defineProperty(exports, "isEmptyDir", { enumerable: true, get: function () { return isEmptyDir_1.isEmptyDir; } });
var copyFiles_1 = require("./copyFiles");
Object.defineProperty(exports, "copyFiles", { enumerable: true, get: function () { return copyFiles_1.copyFiles; } });
var getPackageManager_1 = require("./getPackageManager");
Object.defineProperty(exports, "getPackageManager", { enumerable: true, get: function () { return getPackageManager_1.getPackageManager; } });
+5
View File
@@ -0,0 +1,5 @@
/**
* Returns a boolean telling if a directory is empty or
* not.
*/
export declare function isEmptyDir(location: string): boolean;
+26
View File
@@ -0,0 +1,26 @@
"use strict";
/*
* @adonisjs/sink
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.isEmptyDir = void 0;
const fs_1 = require("fs");
/**
* Returns a boolean telling if a directory is empty or
* not.
*/
function isEmptyDir(location) {
try {
const files = (0, fs_1.readdirSync)(location);
return files.length === 0;
}
catch (error) {
return error.code === 'ENOENT';
}
}
exports.isEmptyDir = isEmptyDir;
+1
View File
@@ -0,0 +1 @@
export {};
+21
View File
@@ -0,0 +1,21 @@
"use strict";
/*
* @adonisjs/sink
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const log_1 = __importDefault(require("mrm-core/src/util/log"));
/**
* Overwriting mrm logger to have support for custom log messages
*/
function noop() { }
log_1.default.info = noop;
log_1.default.removed = noop;
log_1.default.added = noop;