@orxataguy/tyr 1.0.0 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,152 +1,152 @@
1
- import fs from 'fs/promises';
2
- import { existsSync } from 'fs';
3
- import { homedir } from 'os';
4
- import path from 'path';
5
-
6
- import { Logger } from '../core/Logger.js';
7
- import { TyrError } from '../core/TyrError.js';
8
-
9
- /**
10
- * @class FileSystemManager
11
- * @description Abstraction layer over the file system (fs).
12
- * Includes safety utilities such as automatic backups when overwriting and idempotent writes.
13
- */
14
- export class FileSystemManager {
15
- private logger: Logger;
16
-
17
- constructor(logger: Logger) {
18
- this.logger = logger;
19
- }
20
-
21
- private resolvePath(filePath: string): string {
22
- return filePath.startsWith('~/')
23
- ? path.join(homedir(), filePath.slice(2))
24
- : filePath;
25
- }
26
-
27
- /**
28
- * @method exists
29
- * @description Synchronously checks whether a file or directory exists at the given path.
30
- * @param {string} filePath - Relative or absolute path to check.
31
- * @returns {boolean} True if the file exists.
32
- * @example
33
- * if (fs.exists('./config.json')) {
34
- * logger.info('Config found.');
35
- * }
36
- */
37
- public exists(filePath: string): boolean {
38
- const resolvedPath = this.resolvePath(filePath);
39
- return existsSync(resolvedPath);
40
- }
41
-
42
- /**
43
- * @method read
44
- * @description Reads the content of a file in UTF-8 format. Returns null if the file does not exist.
45
- * @param {string} filePath - Path to the file.
46
- * @returns {Promise<string|null>} File content or null if it does not exist.
47
- * @example
48
- * const content = await fs.read('.env');
49
- */
50
- public async read(filePath: string): Promise<string | null> {
51
- const resolvedPath = this.resolvePath(filePath);
52
- try {
53
- return await fs.readFile(resolvedPath, 'utf-8');
54
- } catch (e) {
55
- if ((e as NodeJS.ErrnoException).code === 'ENOENT') return null;
56
- throw new TyrError(`Could not read file: ${filePath}`, e, 'Check that the file exists and has read permissions.');
57
- }
58
- }
59
-
60
- /**
61
- * @method delete
62
- * @description Deletes a file if it exists.
63
- * @param {string} filePath - Path to the file to delete.
64
- * @example
65
- * await fs.delete('./temp/cache.log');
66
- */
67
- public async delete(filePath: string): Promise<void> {
68
- const resolvedPath = this.resolvePath(filePath);
69
- if (!this.exists(resolvedPath)) {
70
- throw new TyrError(`Cannot delete: file not found: ${filePath}`, null, 'Check that the path is correct.');
71
- }
72
- try {
73
- await fs.unlink(resolvedPath);
74
- this.logger.success(`File deleted: ${filePath}`);
75
- } catch (e) {
76
- throw new TyrError(`Could not delete file: ${filePath}`, e);
77
- }
78
- }
79
-
80
- /**
81
- * @method write
82
- * @description Writes content to a file. If the file already exists, creates a .bak backup before overwriting.
83
- * @param {string} filePath - Destination path.
84
- * @param {string} content - Text content to write.
85
- * @example
86
- * await fs.write('src/config.js', 'export const port = 3000;');
87
- */
88
- public async write(filePath: string, content: string): Promise<void> {
89
- const resolvedPath = this.resolvePath(filePath);
90
- try {
91
- const dir = path.dirname(resolvedPath);
92
- await fs.mkdir(dir, { recursive: true });
93
-
94
- if (this.exists(resolvedPath)) {
95
- const backupPath = `${resolvedPath}.bak`;
96
- await fs.copyFile(resolvedPath, backupPath);
97
- this.logger.info(`Backup created at: ${backupPath}`);
98
- }
99
-
100
- await fs.writeFile(resolvedPath, content, 'utf-8');
101
- this.logger.success(`File written: ${filePath}`);
102
- } catch (e) {
103
- if (e instanceof TyrError) throw e;
104
- throw new TyrError(`Could not write file: ${filePath}`, e, 'Check write permissions on the destination directory.');
105
- }
106
- }
107
-
108
- /**
109
- * @method createDir
110
- * @description Creates a directory recursively (like mkdir -p). Does nothing if it already exists.
111
- * @param {string} dirPath - Path of the directory to create.
112
- * @example
113
- * await fs.createDir('src/controllers/api/v1');
114
- */
115
- public async createDir(dirPath: string): Promise<void> {
116
- const resolvedPath = this.resolvePath(dirPath);
117
- if (this.exists(resolvedPath)) return;
118
- try {
119
- await fs.mkdir(resolvedPath, { recursive: true });
120
- this.logger.info(`Directory created: ${dirPath}`);
121
- } catch (e) {
122
- throw new TyrError(`Could not create directory: ${dirPath}`, e, 'Check write permissions on the parent directory.');
123
- }
124
- }
125
-
126
- /**
127
- * @method ensureLine
128
- * @description Ensures that a specific line exists in a file. Useful for adding environment variables or config entries without duplicating them.
129
- * @param {string} filePath - Path to the file.
130
- * @param {string} line - The exact line to ensure.
131
- * @example
132
- * await fs.ensureLine('.env', 'PORT=8080');
133
- */
134
- public async ensureLine(filePath: string, line: string): Promise<void> {
135
- const resolvedPath = this.resolvePath(filePath);
136
- const content = (await this.read(resolvedPath)) || '';
137
- if (content.includes(line)) {
138
- this.logger.info(`Line already present in ${filePath}. Skipping.`);
139
- return;
140
- }
141
- const newContent = content.endsWith('\n') ? content + line : content + '\n' + line;
142
- await this.write(filePath, newContent);
143
- }
144
- }
145
-
146
- export const FileSystemManagerTests = {
147
- exists: { filePath: '~/Projects/TyrFramework/package.json' },
148
- read: { filePath: '~/Projects/TyrFramework/package.json' },
149
- write: { filePath: '~/Projects/TyrFramework/tests/foo.test.txt', content: 'Test content from TyrFramework' },
150
- delete: { filePath: '~/Projects/TyrFramework/tests/foo.test.txt' },
151
- ensureLine: { filePath: '~/Projects/TyrFramework/package.json', line: '"type": "module",' },
152
- };
1
+ import fs from 'fs/promises';
2
+ import { existsSync } from 'fs';
3
+ import { homedir } from 'os';
4
+ import path from 'path';
5
+
6
+ import { Logger } from '../core/Logger.js';
7
+ import { TyrError } from '../core/TyrError.js';
8
+
9
+ /**
10
+ * @class FileSystemManager
11
+ * @description Abstraction layer over the file system (fs).
12
+ * Includes safety utilities such as automatic backups when overwriting and idempotent writes.
13
+ */
14
+ export class FileSystemManager {
15
+ private logger: Logger;
16
+
17
+ constructor(logger: Logger) {
18
+ this.logger = logger;
19
+ }
20
+
21
+ private resolvePath(filePath: string): string {
22
+ return filePath.startsWith('~/')
23
+ ? path.join(homedir(), filePath.slice(2))
24
+ : filePath;
25
+ }
26
+
27
+ /**
28
+ * @method exists
29
+ * @description Synchronously checks whether a file or directory exists at the given path.
30
+ * @param {string} filePath - Relative or absolute path to check.
31
+ * @returns {boolean} True if the file exists.
32
+ * @example
33
+ * if (fs.exists('./config.json')) {
34
+ * logger.info('Config found.');
35
+ * }
36
+ */
37
+ public exists(filePath: string): boolean {
38
+ const resolvedPath = this.resolvePath(filePath);
39
+ return existsSync(resolvedPath);
40
+ }
41
+
42
+ /**
43
+ * @method read
44
+ * @description Reads the content of a file in UTF-8 format. Returns null if the file does not exist.
45
+ * @param {string} filePath - Path to the file.
46
+ * @returns {Promise<string|null>} File content or null if it does not exist.
47
+ * @example
48
+ * const content = await fs.read('.env');
49
+ */
50
+ public async read(filePath: string): Promise<string | null> {
51
+ const resolvedPath = this.resolvePath(filePath);
52
+ try {
53
+ return await fs.readFile(resolvedPath, 'utf-8');
54
+ } catch (e) {
55
+ if ((e as NodeJS.ErrnoException).code === 'ENOENT') return null;
56
+ throw new TyrError(`Could not read file: ${filePath}`, e, 'Check that the file exists and has read permissions.');
57
+ }
58
+ }
59
+
60
+ /**
61
+ * @method delete
62
+ * @description Deletes a file if it exists.
63
+ * @param {string} filePath - Path to the file to delete.
64
+ * @example
65
+ * await fs.delete('./temp/cache.log');
66
+ */
67
+ public async delete(filePath: string): Promise<void> {
68
+ const resolvedPath = this.resolvePath(filePath);
69
+ if (!this.exists(resolvedPath)) {
70
+ throw new TyrError(`Cannot delete: file not found: ${filePath}`, null, 'Check that the path is correct.');
71
+ }
72
+ try {
73
+ await fs.unlink(resolvedPath);
74
+ this.logger.success(`File deleted: ${filePath}`);
75
+ } catch (e) {
76
+ throw new TyrError(`Could not delete file: ${filePath}`, e);
77
+ }
78
+ }
79
+
80
+ /**
81
+ * @method write
82
+ * @description Writes content to a file. If the file already exists, creates a .bak backup before overwriting.
83
+ * @param {string} filePath - Destination path.
84
+ * @param {string} content - Text content to write.
85
+ * @example
86
+ * await fs.write('src/config.js', 'export const port = 3000;');
87
+ */
88
+ public async write(filePath: string, content: string): Promise<void> {
89
+ const resolvedPath = this.resolvePath(filePath);
90
+ try {
91
+ const dir = path.dirname(resolvedPath);
92
+ await fs.mkdir(dir, { recursive: true });
93
+
94
+ if (this.exists(resolvedPath)) {
95
+ const backupPath = `${resolvedPath}.bak`;
96
+ await fs.copyFile(resolvedPath, backupPath);
97
+ this.logger.info(`Backup created at: ${backupPath}`);
98
+ }
99
+
100
+ await fs.writeFile(resolvedPath, content, 'utf-8');
101
+ this.logger.success(`File written: ${filePath}`);
102
+ } catch (e) {
103
+ if (e instanceof TyrError) throw e;
104
+ throw new TyrError(`Could not write file: ${filePath}`, e, 'Check write permissions on the destination directory.');
105
+ }
106
+ }
107
+
108
+ /**
109
+ * @method createDir
110
+ * @description Creates a directory recursively (like mkdir -p). Does nothing if it already exists.
111
+ * @param {string} dirPath - Path of the directory to create.
112
+ * @example
113
+ * await fs.createDir('src/controllers/api/v1');
114
+ */
115
+ public async createDir(dirPath: string): Promise<void> {
116
+ const resolvedPath = this.resolvePath(dirPath);
117
+ if (this.exists(resolvedPath)) return;
118
+ try {
119
+ await fs.mkdir(resolvedPath, { recursive: true });
120
+ this.logger.info(`Directory created: ${dirPath}`);
121
+ } catch (e) {
122
+ throw new TyrError(`Could not create directory: ${dirPath}`, e, 'Check write permissions on the parent directory.');
123
+ }
124
+ }
125
+
126
+ /**
127
+ * @method ensureLine
128
+ * @description Ensures that a specific line exists in a file. Useful for adding environment variables or config entries without duplicating them.
129
+ * @param {string} filePath - Path to the file.
130
+ * @param {string} line - The exact line to ensure.
131
+ * @example
132
+ * await fs.ensureLine('.env', 'PORT=8080');
133
+ */
134
+ public async ensureLine(filePath: string, line: string): Promise<void> {
135
+ const resolvedPath = this.resolvePath(filePath);
136
+ const content = (await this.read(resolvedPath)) || '';
137
+ if (content.includes(line)) {
138
+ this.logger.info(`Line already present in ${filePath}. Skipping.`);
139
+ return;
140
+ }
141
+ const newContent = content.endsWith('\n') ? content + line : content + '\n' + line;
142
+ await this.write(filePath, newContent);
143
+ }
144
+ }
145
+
146
+ export const FileSystemManagerTests = {
147
+ exists: { filePath: '~/Projects/TyrFramework/package.json' },
148
+ read: { filePath: '~/Projects/TyrFramework/package.json' },
149
+ write: { filePath: '~/Projects/TyrFramework/tests/foo.test.txt', content: 'Test content from TyrFramework' },
150
+ delete: { filePath: '~/Projects/TyrFramework/tests/foo.test.txt' },
151
+ ensureLine: { filePath: '~/Projects/TyrFramework/package.json', line: '"type": "module",' },
152
+ };
@@ -1,76 +1,76 @@
1
- import { ShellManager } from './ShellManager.js';
2
- import { Logger } from '../core/Logger.js';
3
- import { TyrError } from '../core/TyrError.js';
4
-
5
- /**
6
- * @class GitManager
7
- * @description Wrapper for common Git operations. Automates repository initialization, commits and cloning.
8
- */
9
- export class GitManager {
10
- private shell: ShellManager;
11
- private logger: Logger;
12
-
13
- constructor(shell: ShellManager, logger: Logger) {
14
- this.shell = shell;
15
- this.logger = logger;
16
- }
17
-
18
- /**
19
- * @method init
20
- * @description Initializes a Git repository in the current directory and renames the default branch to 'main'.
21
- * @example
22
- * await git.init();
23
- */
24
- public async init(): Promise<void> {
25
- try { await this.shell.exec('git init'); await this.shell.exec('git branch -M main'); } catch (e) {
26
- throw new TyrError(`Could not init git repository`, e, 'Check if the current directory still exists.');
27
- }
28
- }
29
-
30
- /**
31
- * @method addAll
32
- * @description Stages all files in the current directory (git add .).
33
- * @example
34
- * await git.addAll();
35
- */
36
- public async addAll(): Promise<void> {
37
- await this.shell.exec('git add .');
38
- }
39
-
40
- /**
41
- * @method commit
42
- * @description Creates a commit with the provided message.
43
- * @param {string} message - The commit message.
44
- * @example
45
- * await git.commit("feat: initial project structure");
46
- */
47
- public async commit(message: string): Promise<void> {
48
- await this.shell.exec(`git commit -m "${message}"`);
49
- this.logger.success(`Commit created: "${message}"`);
50
- }
51
-
52
- /**
53
- * @method clone
54
- * @description Clones a remote repository into the current directory.
55
- * @param {string} repoUrl - The HTTPS or SSH URL of the repository.
56
- * @example
57
- * await git.clone('https://github.com/user/repo.git');
58
- */
59
- public async clone(repoUrl: string): Promise<void> {
60
- this.logger.info(`Cloning ${repoUrl}...`);
61
- try {
62
- await this.shell.exec(`git clone ${repoUrl}`);
63
- } catch (e) {
64
- throw new TyrError(`Could not find the repository ` + repoUrl, e, 'Check if the repository exists or if you have the right permissions to clone it.');
65
- }
66
- }
67
- }
68
-
69
- /**
70
- * @object GitManagerTests
71
- * @description Test parameters to validate GitManager functionality.
72
- */
73
- export const GitManagerTests = {
74
- init: { directory: '/tmp/tyr-git-test' },
75
- addAll: { directory: '/tmp/tyr-git-test' },
1
+ import { ShellManager } from './ShellManager.js';
2
+ import { Logger } from '../core/Logger.js';
3
+ import { TyrError } from '../core/TyrError.js';
4
+
5
+ /**
6
+ * @class GitManager
7
+ * @description Wrapper for common Git operations. Automates repository initialization, commits and cloning.
8
+ */
9
+ export class GitManager {
10
+ private shell: ShellManager;
11
+ private logger: Logger;
12
+
13
+ constructor(shell: ShellManager, logger: Logger) {
14
+ this.shell = shell;
15
+ this.logger = logger;
16
+ }
17
+
18
+ /**
19
+ * @method init
20
+ * @description Initializes a Git repository in the current directory and renames the default branch to 'main'.
21
+ * @example
22
+ * await git.init();
23
+ */
24
+ public async init(): Promise<void> {
25
+ try { await this.shell.exec('git init'); await this.shell.exec('git branch -M main'); } catch (e) {
26
+ throw new TyrError(`Could not init git repository`, e, 'Check if the current directory still exists.');
27
+ }
28
+ }
29
+
30
+ /**
31
+ * @method addAll
32
+ * @description Stages all files in the current directory (git add .).
33
+ * @example
34
+ * await git.addAll();
35
+ */
36
+ public async addAll(): Promise<void> {
37
+ await this.shell.exec('git add .');
38
+ }
39
+
40
+ /**
41
+ * @method commit
42
+ * @description Creates a commit with the provided message.
43
+ * @param {string} message - The commit message.
44
+ * @example
45
+ * await git.commit("feat: initial project structure");
46
+ */
47
+ public async commit(message: string): Promise<void> {
48
+ await this.shell.exec(`git commit -m "${message}"`);
49
+ this.logger.success(`Commit created: "${message}"`);
50
+ }
51
+
52
+ /**
53
+ * @method clone
54
+ * @description Clones a remote repository into the current directory.
55
+ * @param {string} repoUrl - The HTTPS or SSH URL of the repository.
56
+ * @example
57
+ * await git.clone('https://github.com/user/repo.git');
58
+ */
59
+ public async clone(repoUrl: string): Promise<void> {
60
+ this.logger.info(`Cloning ${repoUrl}...`);
61
+ try {
62
+ await this.shell.exec(`git clone ${repoUrl}`);
63
+ } catch (e) {
64
+ throw new TyrError(`Could not find the repository ` + repoUrl, e, 'Check if the repository exists or if you have the right permissions to clone it.');
65
+ }
66
+ }
67
+ }
68
+
69
+ /**
70
+ * @object GitManagerTests
71
+ * @description Test parameters to validate GitManager functionality.
72
+ */
73
+ export const GitManagerTests = {
74
+ init: { directory: '/tmp/tyr-git-test' },
75
+ addAll: { directory: '/tmp/tyr-git-test' },
76
76
  };
@@ -1,87 +1,87 @@
1
- import { ShellManager } from './ShellManager.js';
2
- import { Logger } from '../core/Logger.js';
3
- import { TyrError } from '../core/TyrError.js';
4
-
5
- /**
6
- * @class PackageManager
7
- * @description OS-agnostic package manager. Automatically detects whether the system uses apt, brew or dnf and installs native software.
8
- */
9
- export class PackageManager {
10
- private shell: ShellManager;
11
- private logger: Logger;
12
- private manager: string | null;
13
-
14
- constructor(shell: ShellManager, logger: Logger) {
15
- this.shell = shell;
16
- this.logger = logger;
17
- this.manager = null;
18
- }
19
-
20
- /**
21
- * @method detect
22
- * @description Attempts to identify the package manager installed on the host system.
23
- * @returns {Promise<string>} The name of the detected binary ('apt', 'brew', 'dnf').
24
- * @example
25
- * const mgr = await pkg.detect();
26
- * logger.info(`Using: ${mgr}`);
27
- */
28
- public async detect(): Promise<string> {
29
- if (this.manager) return this.manager;
30
-
31
- const isWindows = process.platform === 'win32';
32
- const checkCmd = isWindows ? 'where' : 'which';
33
-
34
- const candidates: [string, string][] = isWindows
35
- ? [['winget', 'winget'], ['choco', 'choco'], ['scoop', 'scoop']]
36
- : [['apt-get', 'apt'], ['brew', 'brew'], ['dnf', 'dnf']];
37
-
38
- for (const [bin, name] of candidates) {
39
- try {
40
- await this.shell.exec(`${checkCmd} ${bin}`);
41
- this.manager = name;
42
- return name;
43
- } catch (e) {}
44
- }
45
-
46
- throw new TyrError(
47
- 'No supported package manager detected.',
48
- null,
49
- isWindows
50
- ? 'Install winget (Windows Package Manager), Chocolatey, or Scoop.'
51
- : 'Make sure apt, brew or dnf is installed on your system.'
52
- );
53
- }
54
-
55
- /**
56
- * @method install
57
- * @description Installs a system package using the detected package manager.
58
- * @param {string} packageName - Name of the package to install (e.g. 'nginx', 'python3').
59
- * @example
60
- * await pkg.install('nginx');
61
- */
62
- public async install(packageName: string): Promise<void> {
63
- const mgr = await this.detect();
64
- this.logger.info(`Installing ${packageName} using ${mgr}...`);
65
-
66
- const commands: Record<string, string> = {
67
- apt: `sudo apt-get install -y ${packageName}`,
68
- brew: `brew install ${packageName}`,
69
- dnf: `sudo dnf install -y ${packageName}`,
70
- winget: `winget install ${packageName}`,
71
- choco: `choco install -y ${packageName}`,
72
- scoop: `scoop install ${packageName}`,
73
- };
74
-
75
- try {
76
- await this.shell.exec(commands[mgr]);
77
- this.logger.success(`Package ${packageName} installed.`);
78
- } catch (e) {
79
- if (e instanceof TyrError) throw e;
80
- throw new TyrError(`Could not install package: ${packageName}`, e, `Try running the install command manually with ${mgr}.`);
81
- }
82
- }
83
- }
84
-
85
- export const PackageManagerTests = {
86
- detect: {},
87
- };
1
+ import { ShellManager } from './ShellManager.js';
2
+ import { Logger } from '../core/Logger.js';
3
+ import { TyrError } from '../core/TyrError.js';
4
+
5
+ /**
6
+ * @class PackageManager
7
+ * @description OS-agnostic package manager. Automatically detects whether the system uses apt, brew or dnf and installs native software.
8
+ */
9
+ export class PackageManager {
10
+ private shell: ShellManager;
11
+ private logger: Logger;
12
+ private manager: string | null;
13
+
14
+ constructor(shell: ShellManager, logger: Logger) {
15
+ this.shell = shell;
16
+ this.logger = logger;
17
+ this.manager = null;
18
+ }
19
+
20
+ /**
21
+ * @method detect
22
+ * @description Attempts to identify the package manager installed on the host system.
23
+ * @returns {Promise<string>} The name of the detected binary ('apt', 'brew', 'dnf').
24
+ * @example
25
+ * const mgr = await pkg.detect();
26
+ * logger.info(`Using: ${mgr}`);
27
+ */
28
+ public async detect(): Promise<string> {
29
+ if (this.manager) return this.manager;
30
+
31
+ const isWindows = process.platform === 'win32';
32
+ const checkCmd = isWindows ? 'where' : 'which';
33
+
34
+ const candidates: [string, string][] = isWindows
35
+ ? [['winget', 'winget'], ['choco', 'choco'], ['scoop', 'scoop']]
36
+ : [['apt-get', 'apt'], ['brew', 'brew'], ['dnf', 'dnf']];
37
+
38
+ for (const [bin, name] of candidates) {
39
+ try {
40
+ await this.shell.exec(`${checkCmd} ${bin}`);
41
+ this.manager = name;
42
+ return name;
43
+ } catch (e) {}
44
+ }
45
+
46
+ throw new TyrError(
47
+ 'No supported package manager detected.',
48
+ null,
49
+ isWindows
50
+ ? 'Install winget (Windows Package Manager), Chocolatey, or Scoop.'
51
+ : 'Make sure apt, brew or dnf is installed on your system.'
52
+ );
53
+ }
54
+
55
+ /**
56
+ * @method install
57
+ * @description Installs a system package using the detected package manager.
58
+ * @param {string} packageName - Name of the package to install (e.g. 'nginx', 'python3').
59
+ * @example
60
+ * await pkg.install('nginx');
61
+ */
62
+ public async install(packageName: string): Promise<void> {
63
+ const mgr = await this.detect();
64
+ this.logger.info(`Installing ${packageName} using ${mgr}...`);
65
+
66
+ const commands: Record<string, string> = {
67
+ apt: `sudo apt-get install -y ${packageName}`,
68
+ brew: `brew install ${packageName}`,
69
+ dnf: `sudo dnf install -y ${packageName}`,
70
+ winget: `winget install ${packageName}`,
71
+ choco: `choco install -y ${packageName}`,
72
+ scoop: `scoop install ${packageName}`,
73
+ };
74
+
75
+ try {
76
+ await this.shell.exec(commands[mgr]);
77
+ this.logger.success(`Package ${packageName} installed.`);
78
+ } catch (e) {
79
+ if (e instanceof TyrError) throw e;
80
+ throw new TyrError(`Could not install package: ${packageName}`, e, `Try running the install command manually with ${mgr}.`);
81
+ }
82
+ }
83
+ }
84
+
85
+ export const PackageManagerTests = {
86
+ detect: {},
87
+ };