@uss-stargazer/job-queue 0.0.1

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.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright {yyyy} {name of copyright owner}
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,33 @@
1
+ # Job Queue
2
+
3
+ The concept is modeling your todo-list as bite-sized jobs in a First-In, First-Out (FIFO) queue.
4
+ The goal is to increase productivity.
5
+
6
+ - Small jobs that do one thing at a time are more manageable, and make Git commits easier
7
+ - Documenting todo in manageable fashion decreases liklihood of abandoning a project
8
+
9
+ ## Install
10
+
11
+ Can be installed system-wide if you have Node/NPM installed:
12
+
13
+ ```
14
+ npm install --global @uss-stargazer/job-queue
15
+ ```
16
+
17
+ Then, you can use like:
18
+
19
+ ```
20
+ job-queue --help
21
+ # or
22
+ jobq --help
23
+ ```
24
+
25
+ ## Workflow
26
+
27
+ - _\[Daemon\]_ Spontaneous, not fleshed out ideas get immediately added to the project pool as "inactive".
28
+ - You should generally have an idea of a few projects you want to focus on at a time. For each, push
29
+ jobs to the jobqueue that do a **_single thing_** (ideally no more; they should be contained in a
30
+ single Git commit).
31
+ - Work (while you haven't finished the projects you're focusing on)
32
+ - Go through job queue and remove jobs when complete (committing as you go).
33
+ - _\[Daemon\]_ While not on the terminal, think of next jobs, then push to queue.
@@ -0,0 +1,180 @@
1
+ import chalk from 'chalk';
2
+ import { confirm, search } from '@inquirer/prompts';
3
+ import sortableCheckbox from './utils/sortableCheckbox.js';
4
+ import { AbortError, reorder } from './utils/index.js';
5
+ import { updateJob } from './data/jobqueue.js';
6
+ import { updateProject } from './data/projectpool.js';
7
+ export const actionNames = [
8
+ 'dequeueJob',
9
+ 'enqueueJob',
10
+ 'editQueue',
11
+ 'addProject',
12
+ 'editProject',
13
+ ];
14
+ export const actionsDependentOnJobs = ['dequeueJob', 'editQueue'];
15
+ export const actionsDependentOnProjects = [
16
+ 'enqueueJob',
17
+ 'editProject',
18
+ ];
19
+ const actions = {
20
+ dequeueJob: async ({ jobqueue, projectpool, config }) => {
21
+ const queue = jobqueue.data.queue;
22
+ const job = queue.shift();
23
+ if (job === undefined) {
24
+ console.log(chalk.red('[e]'), 'No jobs in queue.');
25
+ return;
26
+ }
27
+ try {
28
+ const updatedJob = await updateJob(job, projectpool, config.data);
29
+ if (updatedJob !== 'deleted') {
30
+ queue.unshift(updatedJob);
31
+ console.log(chalk.blue('[i]'), 'Job edited');
32
+ }
33
+ else {
34
+ console.log(chalk.green('✔'), 'Job completed and deleted');
35
+ }
36
+ await jobqueue.sync();
37
+ }
38
+ catch (error) {
39
+ if (!(error instanceof AbortError))
40
+ throw error;
41
+ console.log(chalk.red('[e]'), error.message);
42
+ queue.unshift(job);
43
+ }
44
+ },
45
+ enqueueJob: async ({ jobqueue, projectpool, config }) => {
46
+ if (projectpool.data.pool.length === 0) {
47
+ console.log(chalk.red('[e]'), 'No projects in pool to make job for.');
48
+ return;
49
+ }
50
+ const queue = jobqueue.data.queue;
51
+ const placeholderJob = {
52
+ name: '[placeholder]',
53
+ objectivies: [
54
+ 'Put the thing in the thing.',
55
+ 'Make sure that thing works.',
56
+ ],
57
+ project: '[some-project]',
58
+ updates: 'Put notes here.',
59
+ };
60
+ try {
61
+ const job = await updateJob(placeholderJob, projectpool, config.data);
62
+ if (job === 'deleted')
63
+ throw new AbortError('Enqueue aborted');
64
+ queue.push(job);
65
+ console.log(chalk.green('✔'), 'Job enqueued');
66
+ await jobqueue.sync();
67
+ }
68
+ catch (error) {
69
+ if (!(error instanceof AbortError))
70
+ throw error;
71
+ console.log(chalk.red('[e]'), error.message);
72
+ }
73
+ },
74
+ editQueue: async ({ jobqueue, projectpool, config }) => {
75
+ const queue = jobqueue.data.queue;
76
+ if (queue.length === 0) {
77
+ console.log(chalk.red('[e]'), 'No jobs in queue.');
78
+ return;
79
+ }
80
+ const reorderedQueueIdxs = await sortableCheckbox({
81
+ message: 'Reorder queue and/or select jobs to edit',
82
+ choices: queue.map((job, jobIdx) => ({
83
+ name: `[${job.project}] ${job.name}`,
84
+ value: jobIdx,
85
+ })),
86
+ });
87
+ reorder(queue, reorderedQueueIdxs.map(({ value: jobIdx }) => jobIdx));
88
+ console.log(chalk.green('✔'), 'Queue reordered.');
89
+ const checkedActivities = reorderedQueueIdxs
90
+ .map(({ checked }, jobIdx) => ({ checked, jobIdx }))
91
+ .filter(({ checked }) => checked);
92
+ if (checkedActivities.length > 0) {
93
+ for (let checkedIdx = 0; checkedIdx < checkedActivities.length; checkedIdx++) {
94
+ const jobIdx = checkedActivities[checkedIdx].jobIdx;
95
+ try {
96
+ const job = queue[jobIdx];
97
+ const updatedJob = await updateJob(job, projectpool, config.data);
98
+ if (updatedJob === 'deleted') {
99
+ queue.splice(jobIdx, 1);
100
+ console.log(chalk.green('✔'), `Job '${job.name}' deleted.`);
101
+ }
102
+ else {
103
+ queue[jobIdx] = updatedJob;
104
+ console.log(chalk.green('✔'), `Job '${updatedJob.name}' edited.`);
105
+ }
106
+ await jobqueue.sync();
107
+ }
108
+ catch (error) {
109
+ if (!(error instanceof AbortError))
110
+ throw error;
111
+ console.log(chalk.red('[e]'), error.message);
112
+ if (checkedIdx + 1 < checkedActivities.length &&
113
+ (await confirm({ message: 'Abort all edits?' })))
114
+ break;
115
+ }
116
+ }
117
+ }
118
+ },
119
+ addProject: async ({ jobqueue, projectpool, config }) => {
120
+ const pool = projectpool.data.pool;
121
+ const placeholderProject = {
122
+ name: '[some-project]',
123
+ description: 'This is a placeholder project.',
124
+ repo: 'https://some.project.com/project',
125
+ status: 'inactive',
126
+ };
127
+ try {
128
+ const project = await updateProject(placeholderProject, projectpool, jobqueue, config.data);
129
+ if (project === 'deleted')
130
+ throw new AbortError('Add project aborted');
131
+ pool.push(project);
132
+ console.log(chalk.green('✔'), 'Added new project');
133
+ await projectpool.sync();
134
+ }
135
+ catch (error) {
136
+ if (!(error instanceof AbortError))
137
+ throw error;
138
+ console.log(chalk.red('[e]'), error.message);
139
+ }
140
+ },
141
+ editProject: async ({ jobqueue, projectpool, config }) => {
142
+ const pool = projectpool.data.pool;
143
+ if (pool.length === 0) {
144
+ console.log(chalk.red('[e]'), 'No projects in pool.');
145
+ return;
146
+ }
147
+ const projectName = await search({
148
+ message: 'Enter the name of the project to edit',
149
+ source: (partialProjectName) => {
150
+ const projectNames = pool.map((project) => project.name);
151
+ if (!partialProjectName)
152
+ return projectNames;
153
+ const partialSet = new Set([...partialProjectName]);
154
+ return projectNames.filter((projectName) => partialSet.isSubsetOf(new Set([...projectName])));
155
+ },
156
+ });
157
+ const projectIdx = pool.findIndex((project) => project.name === projectName);
158
+ if (projectIdx < 0)
159
+ throw new Error('Invalid project name');
160
+ const [project] = pool.splice(projectIdx, 1);
161
+ try {
162
+ const updatedProject = await updateProject(project, projectpool, jobqueue, config.data);
163
+ if (updatedProject !== 'deleted') {
164
+ pool.push(updatedProject);
165
+ console.log(chalk.green('✔'), 'Project edited');
166
+ }
167
+ else {
168
+ console.log(chalk.green('✔'), 'Project deleted');
169
+ }
170
+ await projectpool.sync();
171
+ }
172
+ catch (error) {
173
+ if (error instanceof AbortError)
174
+ throw error;
175
+ console.log(chalk.red('[e]'), error.message);
176
+ pool.push(project);
177
+ }
178
+ },
179
+ };
180
+ export default actions;
@@ -0,0 +1,158 @@
1
+ import * as z from 'zod';
2
+ import envPaths from 'env-paths';
3
+ import path from 'path';
4
+ import fs from 'fs/promises';
5
+ import { existsSync } from 'fs';
6
+ import { makeJsonData } from '../utils/jsonData.js';
7
+ import chalk from 'chalk';
8
+ import { JobQueueSchema, JobSchema } from './jobqueue.js';
9
+ import { ProjectPoolSchema, ProjectSchema, } from './projectpool.js';
10
+ import { confirm } from '@inquirer/prompts';
11
+ import { fileURLToPath, pathToFileURL } from 'url';
12
+ import pkg from '../../package.json' with { type: 'json' };
13
+ const jsonSchemaNames = [
14
+ 'job',
15
+ 'jobqueue',
16
+ 'project',
17
+ 'projectpool',
18
+ 'config',
19
+ ];
20
+ const NonemptyString = z.string().nonempty();
21
+ export const ConfigSchema = z.object({
22
+ jobqueue: NonemptyString.optional().meta({ title: "Jobqueue path", description: "Path to jobqueue.json." }),
23
+ projectpool: NonemptyString.optional().meta({ title: "Projectpool path", description: "Path to projectpool.json." }),
24
+ editor: NonemptyString.optional().meta({ title: "Editor command", description: "Command to run editor. Will be run like `<editor> /some/data.json` so make sure it waits." }),
25
+ schemas: NonemptyString.meta({ title: "Schemas directory", description: `Path to directory containing: ${jsonSchemaNames.map(base => `${base}.schema.json`).join(", ")}.` }).transform((schemasDir) => Object.fromEntries(jsonSchemaNames.map((base) => [base, pathToFileURL(path.resolve(schemasDir, `${base}.schema.json`)).href]))),
26
+ });
27
+ const jsonSchemas = {
28
+ job: JobSchema,
29
+ jobqueue: JobQueueSchema,
30
+ project: ProjectSchema,
31
+ projectpool: ProjectPoolSchema,
32
+ config: ConfigSchema,
33
+ };
34
+ const updateNestedObject = async (base, update) => {
35
+ const keys = [...Object.keys(update)];
36
+ for (const key of keys) {
37
+ if (typeof base[key] === 'object' &&
38
+ base[key] !== null &&
39
+ !Array.isArray(base[key])) {
40
+ await updateNestedObject(base[key], update[key]);
41
+ }
42
+ else {
43
+ const shouldUpdate = await confirm({
44
+ message: `Supplied '${key.toString()}' is different than in config. Want to update config?`,
45
+ });
46
+ if (shouldUpdate)
47
+ base[key] = update[key];
48
+ }
49
+ }
50
+ };
51
+ const getJsonSchemaId = (schemaFileUrl) => path.posix.join(pkg.version, path.basename(fileURLToPath(schemaFileUrl)));
52
+ const versionFromJsonSchemaId = (id) => path.dirname(id);
53
+ const updateJsonSchema = async (schemaSchema, schemaFileUrl) => {
54
+ const schemaPath = fileURLToPath(schemaFileUrl);
55
+ await fs.mkdir(path.dirname(schemaPath), { recursive: true });
56
+ return await fs.writeFile(schemaPath, JSON.stringify({
57
+ $id: getJsonSchemaId(schemaFileUrl),
58
+ ...schemaSchema.toJSONSchema({
59
+ io: 'input',
60
+ unrepresentable: 'throw',
61
+ }),
62
+ }, undefined, ' '));
63
+ };
64
+ const defaultData = {
65
+ jobqueue: { queue: [] },
66
+ projectpool: { pool: [] },
67
+ };
68
+ const createConfig = async (configDir, override) => {
69
+ const config = {
70
+ jobqueue: path.resolve(configDir, 'jobqueue.json'),
71
+ projectpool: path.resolve(configDir, 'projectpool.json'),
72
+ schemas: path.resolve(configDir, 'schemas'),
73
+ ...override,
74
+ };
75
+ const decodedConfig = ConfigSchema.decode(config);
76
+ for (const key of ['jobqueue', 'projectpool']) {
77
+ if (!existsSync(config[key])) {
78
+ console.log(chalk.blue('[i]'), `Creating ${path.join('{config}', path.relative(configDir, config[key]))}...`);
79
+ await fs.writeFile(config[key], JSON.stringify({
80
+ $schema: decodedConfig.schemas[key],
81
+ ...defaultData[key],
82
+ }, undefined, ' '));
83
+ }
84
+ }
85
+ await fs.mkdir(config.schemas);
86
+ for (const schema of jsonSchemaNames) {
87
+ if (!existsSync(decodedConfig.schemas[schema])) {
88
+ console.log(chalk.blue('[i]'), `Creating ${path.join('{config}', path.relative(configDir, fileURLToPath(decodedConfig.schemas[schema])))}...`);
89
+ await updateJsonSchema(jsonSchemas[schema], decodedConfig.schemas[schema]);
90
+ }
91
+ }
92
+ return { encoded: config, decoded: decodedConfig };
93
+ };
94
+ const checkConfig = async (config, configPath) => {
95
+ try {
96
+ for (const key of ['jobqueue', 'projectpool']) {
97
+ if (!existsSync(config[key]))
98
+ if (['jobqueue', 'projectpool'].includes(key) &&
99
+ (await confirm({
100
+ message: `File at config.${key} does not exist. Want to create it?`,
101
+ })))
102
+ await fs.writeFile(config[key], JSON.stringify({
103
+ $schema: config.schemas[key],
104
+ ...defaultData[key],
105
+ }, undefined, ' '));
106
+ else
107
+ throw new Error(`File '${config[key]}' in config does not exist`);
108
+ }
109
+ const outdatedSchemas = [];
110
+ for (const schema of Object.keys(config.schemas)) {
111
+ const schemaPath = fileURLToPath(config.schemas[schema]);
112
+ if (existsSync(schemaPath)) {
113
+ const schemaJson = JSON.parse(await fs.readFile(schemaPath, {
114
+ encoding: 'utf8',
115
+ }));
116
+ const version = schemaJson.$id && versionFromJsonSchemaId(schemaJson.$id);
117
+ if (!version || !/^\d+\.\d+\.\d+$/.test(version)) {
118
+ console.log(chalk.yellow('[w]'), `${path.join('{config}', path.basename(config.schemas[schema]))} is malformed. Overwriting...`);
119
+ await updateJsonSchema(jsonSchemas[schema], config.schemas[schema]);
120
+ }
121
+ else if (version !== pkg.version) {
122
+ outdatedSchemas.push(schema);
123
+ }
124
+ }
125
+ else {
126
+ console.log(chalk.blue('[i]'), `${path.join('{config}', path.basename(config.schemas[schema]))} does not exist. Creating...`);
127
+ await updateJsonSchema(jsonSchemas[schema], config.schemas[schema]);
128
+ }
129
+ }
130
+ if (outdatedSchemas.length > 0) {
131
+ const shouldUpdate = await confirm({
132
+ message: 'You are using at least one outdated JSON schema. Want to regenerate them?',
133
+ });
134
+ if (shouldUpdate)
135
+ outdatedSchemas.forEach((schema) => updateJsonSchema(jsonSchemas[schema], config.schemas[schema]));
136
+ }
137
+ }
138
+ catch (error) {
139
+ throw new Error(`${error}\nFix config at '${configPath}'.`);
140
+ }
141
+ };
142
+ export const getConfig = async (overrideConfigDir, overrideConfig) => {
143
+ const configDir = overrideConfigDir ?? path.resolve(envPaths('job-queue').config);
144
+ const configPath = path.resolve(configDir, 'config.json');
145
+ await fs.mkdir(configDir, { recursive: true });
146
+ if (!existsSync(configPath)) {
147
+ console.log(chalk.blue('[i]'), `Creating config at '${configPath}'...`);
148
+ const { encoded: config, decoded: decodedConfig } = await createConfig(configDir, overrideConfig);
149
+ await fs.writeFile(configPath, JSON.stringify({
150
+ $schema: decodedConfig.schemas['config'],
151
+ ...config,
152
+ }, undefined, ' '));
153
+ }
154
+ const configData = await makeJsonData(configPath, ConfigSchema);
155
+ await checkConfig(configData.data, configPath);
156
+ await updateNestedObject(configData.data, ConfigSchema.partial().decode(overrideConfig));
157
+ return configData;
158
+ };
@@ -0,0 +1,9 @@
1
+ import { JobQueueSchema } from './jobqueue.js';
2
+ import { ProjectPoolSchema } from './projectpool.js';
3
+ import { ConfigSchema } from './config.js';
4
+ export const dataNames = ['jobqueue', 'projectpool', 'config'];
5
+ export const dataSchemas = {
6
+ jobqueue: JobQueueSchema,
7
+ projectpool: ProjectPoolSchema,
8
+ config: ConfigSchema,
9
+ };
@@ -0,0 +1,51 @@
1
+ import * as z from 'zod';
2
+ import { makeJsonData } from '../utils/jsonData.js';
3
+ import { checkProjectName } from './projectpool.js';
4
+ import { haveUserUpdateData } from '../utils/index.js';
5
+ export const JobSchema = z.object({
6
+ name: z.string().trim().nonempty().meta({ title: 'Job name', description: 'Short name of the job (think a single commit message). Used as job identifier.' }),
7
+ objectivies: z.array(z.string().trim().nonempty()).meta({ title: 'Job objectivies', description: 'A list of objectives to complete for this job. Purely for your benefit.' }),
8
+ updates: z.string().optional().meta({ title: 'Job updates', description: "Put any notes/updates to the job here while you're working. Optional." }),
9
+ project: z.string().trim().nonempty().meta({ title: 'Associated project', description: 'Corresponding project ID in projectpool.json.' }),
10
+ }).meta({ title: 'Job', description: 'A single job entry for JobQueue.' });
11
+ export const JobQueueSchema = z.object({
12
+ queue: z.array(JobSchema).meta({ title: 'Job queue' }),
13
+ }).meta({ title: 'Job queue root', description: 'Root object for jobs/tasks FIFO queue model.' });
14
+ export const getJobQueue = async (jsonPath) => await makeJsonData(jsonPath, JobQueueSchema);
15
+ export const updateJob = async (job, projectPool, config) => {
16
+ const pool = projectPool.data.pool;
17
+ let userDeletedJob = false;
18
+ const updatedJob = await haveUserUpdateData(JobSchema, job, {
19
+ editor: config.editor,
20
+ errorHead: 'Rejected job',
21
+ file: { type: 'tmp', prefix: 'jobqueue-job' },
22
+ tooltips: [
23
+ 'Opening job JSON in editor for editing.',
24
+ 'Delete file contents to finish the job.',
25
+ ],
26
+ jsonSchemaUrl: config.schemas.job,
27
+ }, {
28
+ preparse(rawContents) {
29
+ if (rawContents.trim().length === 0) {
30
+ userDeletedJob = true;
31
+ return 'pass';
32
+ }
33
+ return 'continue';
34
+ },
35
+ postparse(job) {
36
+ return checkProjectName(job.project, pool)
37
+ ? 'continue'
38
+ : {
39
+ errMessage: `invalid project name: '${job.project}' not in project pool`,
40
+ };
41
+ },
42
+ });
43
+ if (!userDeletedJob) {
44
+ const jobProject = pool.find((project) => project.name === updatedJob.project);
45
+ if (jobProject.status !== 'active') {
46
+ jobProject.status = 'active';
47
+ await projectPool.sync();
48
+ }
49
+ }
50
+ return userDeletedJob ? 'deleted' : updatedJob;
51
+ };
@@ -0,0 +1,65 @@
1
+ import { confirm } from '@inquirer/prompts';
2
+ import * as z from 'zod';
3
+ import { makeJsonData } from '../utils/jsonData.js';
4
+ import { haveUserUpdateData } from '../utils/index.js';
5
+ export const ProjectSchema = z.object({
6
+ name: z.string().trim().nonempty().meta({ title: 'Project name', description: 'Name of the project. Used as identifier.' }),
7
+ description: z.string().optional().meta({ title: 'Project description', description: 'Longer description of the project. For your benefit, optional.' }),
8
+ repo: z.url().optional().meta({ title: 'Project repository', description: 'URL to project repository. For your benefit, optional.' }),
9
+ status: z.enum(['active', 'inactive', 'complete']).meta({ title: 'Project status', description: "Status of this project. 'active': they are referenced in jobqueue.json, 'inactive': they aren't referenced anywhere and aren't done, 'complete': they're done." }),
10
+ }).meta({ title: 'Project', description: 'A single project entry for JobQueue (usually matches up with a GitHub repo, if you use that).' });
11
+ export const ProjectPoolSchema = z.object({
12
+ pool: z.array(ProjectSchema).meta({ description: 'Set of projects, works in progress or just ideas.' }),
13
+ }).meta({ title: 'Root project pool', description: 'Root object for pool of projects.' });
14
+ export const getProjectPool = async (jsonPath) => await makeJsonData(jsonPath, ProjectPoolSchema);
15
+ export const checkProjectName = (name, projects) => projects.some((project) => project.name === name);
16
+ export const updateProject = async (project, projectPool, jobQueue, config) => {
17
+ const pool = projectPool.data.pool;
18
+ const jobsReferencingProject = jobQueue.data.queue.filter((job) => job.project === project.name);
19
+ let userDeletedProject = false;
20
+ const updatedProject = await haveUserUpdateData(ProjectSchema, project, {
21
+ editor: config.editor,
22
+ errorHead: 'Rejected project',
23
+ file: { type: 'tmp', prefix: 'jobqueue-project' },
24
+ tooltips: [
25
+ 'Opening project JSON in editor for editing.',
26
+ 'Delete file contents to delete the project.',
27
+ ],
28
+ jsonSchemaUrl: config.schemas.project,
29
+ }, {
30
+ preparse(rawContents) {
31
+ if (rawContents.trim().length === 0) {
32
+ userDeletedProject = true;
33
+ return 'pass';
34
+ }
35
+ return 'continue';
36
+ },
37
+ postparse(updatedProject) {
38
+ if (updatedProject.name !== project.name &&
39
+ checkProjectName(updatedProject.name, pool))
40
+ return {
41
+ errMessage: `new name '${updatedProject.name}' already exists in pool`,
42
+ };
43
+ if (jobsReferencingProject.length > 0 &&
44
+ updatedProject.status !== 'active')
45
+ return {
46
+ errMessage: `status can not be set to ${updatedProject.status}: jobs in queue still reference project`,
47
+ };
48
+ return 'continue';
49
+ },
50
+ });
51
+ if (!userDeletedProject &&
52
+ updatedProject.name !== project.name &&
53
+ jobsReferencingProject.length > 0) {
54
+ const renameJobReferences = await confirm({
55
+ message: `You are changing this project's name to ${updatedProject.name}. Would you like to rename the project entry in referencing jobs?`,
56
+ });
57
+ if (renameJobReferences) {
58
+ jobsReferencingProject.forEach((job) => {
59
+ job.project = updatedProject.name;
60
+ });
61
+ await jobQueue.sync();
62
+ }
63
+ }
64
+ return userDeletedProject ? 'deleted' : updatedProject;
65
+ };
package/dist/index.js ADDED
@@ -0,0 +1,51 @@
1
+ import chalk from 'chalk';
2
+ import clear from 'clear';
3
+ import figlet from 'figlet';
4
+ import { select } from '@inquirer/prompts';
5
+ import { ExitPromptError } from '@inquirer/core';
6
+ import actions, { actionNames, actionsDependentOnJobs, actionsDependentOnProjects, } from './actions.js';
7
+ import { getConfig } from './data/config.js';
8
+ import { getJobQueue } from './data/jobqueue.js';
9
+ import { getProjectPool } from './data/projectpool.js';
10
+ export default async function main(overrideConfigDir, overrideConfig) {
11
+ clear();
12
+ console.log(chalk.yellow(figlet.textSync('JobQueue', { horizontalLayout: 'full' })));
13
+ const config = await getConfig(overrideConfigDir, overrideConfig);
14
+ const data = {
15
+ config: config,
16
+ jobqueue: await getJobQueue(config.data.jobqueue),
17
+ projectpool: await getProjectPool(config.data.projectpool),
18
+ };
19
+ console.log();
20
+ try {
21
+ while (true) {
22
+ const action = await select({
23
+ message: 'Select action',
24
+ choices: actionNames.map((action) => {
25
+ if (actionsDependentOnJobs.includes(action) &&
26
+ data.jobqueue.data.queue.length === 0)
27
+ return {
28
+ name: action,
29
+ value: action,
30
+ disabled: '(Empty job queue)',
31
+ };
32
+ else if (actionsDependentOnProjects.includes(action) &&
33
+ data.projectpool.data.pool.length === 0)
34
+ return {
35
+ name: action,
36
+ value: action,
37
+ disabled: '(Empty project pool)',
38
+ };
39
+ else
40
+ return { name: action, value: action };
41
+ }),
42
+ });
43
+ await actions[action](data);
44
+ console.log();
45
+ }
46
+ }
47
+ catch (error) {
48
+ if (!(error instanceof ExitPromptError))
49
+ throw error;
50
+ }
51
+ }
@@ -0,0 +1,83 @@
1
+ import * as tmp from 'tmp-promise';
2
+ import chalk from 'chalk';
3
+ import * as z from 'zod';
4
+ import { confirm } from '@inquirer/prompts';
5
+ import { editInteractively } from 'edit-like-git';
6
+ export class AbortError extends Error {
7
+ constructor(message) {
8
+ super(message);
9
+ }
10
+ }
11
+ export function reorder(array, newIndecies) {
12
+ if (array.length !== newIndecies.length)
13
+ throw new RangeError('Indecies array must be same length as target array');
14
+ const originalArray = [...array];
15
+ newIndecies.forEach((originalIdx, idx) => {
16
+ array[idx] = originalArray[originalIdx];
17
+ });
18
+ }
19
+ export const haveUserUpdateData = async (schema, data, options, checks) => {
20
+ const file = options?.file?.type && options.file.type === 'abs'
21
+ ? { path: options.file.path }
22
+ : await tmp.file({
23
+ prefix: options?.file?.type === 'tmp' ? options.file.prefix : undefined,
24
+ postfix: '.json',
25
+ });
26
+ let contents = JSON.stringify(schema instanceof z.ZodObject && options?.jsonSchemaUrl
27
+ ? { $schema: options?.jsonSchemaUrl, ...data }
28
+ : data, undefined, ' ');
29
+ let updatedResult = undefined;
30
+ while (true) {
31
+ const controller = new AbortController();
32
+ const signal = controller.signal;
33
+ const editorPromise = editInteractively(file.path, contents, options?.editor, options?.tooltips);
34
+ await new Promise((resolve) => setTimeout(resolve, 1000));
35
+ const abortPromise = confirm({ message: 'Type `y` to abort...' }, { signal })
36
+ .finally(() => {
37
+ process.stdout.moveCursor(0, -1);
38
+ process.stdout.clearLine(1);
39
+ })
40
+ .then(async (shouldAbort) => {
41
+ if (shouldAbort) {
42
+ if (file.cleanup)
43
+ await file.cleanup();
44
+ throw new AbortError('User aborted action');
45
+ }
46
+ });
47
+ contents = await Promise.race([editorPromise, abortPromise]);
48
+ controller.abort();
49
+ if (typeof contents !== 'string')
50
+ return undefined;
51
+ if (checks?.preparse) {
52
+ const preparseError = checks?.preparse(contents);
53
+ if (preparseError === 'pass') {
54
+ updatedResult = undefined;
55
+ break;
56
+ }
57
+ else if (typeof preparseError === 'object') {
58
+ console.log(chalk.red(`${options?.errorHead}:`), preparseError.errMessage);
59
+ continue;
60
+ }
61
+ }
62
+ updatedResult = schema.safeParse(JSON.parse(contents));
63
+ if (updatedResult.success) {
64
+ if (checks?.postparse) {
65
+ const postparseError = checks?.postparse(updatedResult.data);
66
+ if (typeof postparseError === 'object') {
67
+ console.log(chalk.red(`${options?.errorHead}:`), postparseError.errMessage);
68
+ continue;
69
+ }
70
+ }
71
+ break;
72
+ }
73
+ console.log(chalk.red(`${options?.errorHead}:`), `JSON invalid: ${updatedResult.error.message}`);
74
+ }
75
+ if (file.cleanup)
76
+ await file.cleanup();
77
+ return (updatedResult &&
78
+ (updatedResult.success
79
+ ? updatedResult.data
80
+ : (() => {
81
+ throw new Error(`${options?.errorHead}: JSON invalid: ${updatedResult.error.message}`);
82
+ })()));
83
+ };
@@ -0,0 +1,24 @@
1
+ import fs from 'fs/promises';
2
+ import * as z from 'zod';
3
+ export const makeJsonData = async (jsonPath, schema) => {
4
+ const json = JSON.parse(await fs.readFile(jsonPath, 'utf8').catch((error) => {
5
+ throw new Error(`Couldn't open '${jsonPath}': ${error}`);
6
+ }));
7
+ const schemaUrl = json['$schema'];
8
+ const parsed = schema.safeParse(json);
9
+ if (!parsed.success)
10
+ throw new Error(`JSON at '${jsonPath}' does not match schema: ${z.treeifyError(parsed.error)}`);
11
+ const jsonData = {
12
+ data: parsed.data,
13
+ async sync() {
14
+ const encoded = schema.encode(jsonData.data);
15
+ return fs.writeFile(jsonPath, JSON.stringify(typeof schemaUrl === 'string'
16
+ ? {
17
+ $schema: schemaUrl,
18
+ ...encoded,
19
+ }
20
+ : encoded, undefined, ' '), 'utf8');
21
+ },
22
+ };
23
+ return jsonData;
24
+ };
@@ -0,0 +1,197 @@
1
+ import { createPrompt, useState, useKeypress, usePrefix, usePagination, useRef, useMemo, makeTheme, isUpKey, isDownKey, isSpaceKey, isNumberKey, isEnterKey, ValidationError, } from '@inquirer/core';
2
+ import chalk from 'chalk';
3
+ import figures from '@inquirer/figures';
4
+ import ansiEscapes from 'ansi-escapes';
5
+ const checkboxTheme = {
6
+ icon: {
7
+ checked: chalk.green(figures.circleFilled),
8
+ unchecked: figures.circle,
9
+ cursor: figures.pointer,
10
+ },
11
+ style: {
12
+ disabledChoice: (text) => chalk.dim(`- ${text}`),
13
+ renderSelectedChoices: (selectedChoices) => selectedChoices.map((choice) => choice.name || choice.value).join(', '),
14
+ },
15
+ helpMode: 'auto',
16
+ };
17
+ export default createPrompt((config, done) => {
18
+ const { instructions, pageSize = 7, choices, required, validate = () => true, } = config;
19
+ const theme = makeTheme(checkboxTheme, config.theme);
20
+ const prefix = usePrefix({ theme });
21
+ const firstRender = useRef(true);
22
+ const [status, setStatus] = useState('pending');
23
+ const [items, setItems] = useState(choices.map((choice) => ({ ...choice })));
24
+ const bounds = useMemo(() => {
25
+ const first = items.findIndex(isSelectable);
26
+ const last = items.findLastIndex(isSelectable);
27
+ if (first < 0) {
28
+ throw new ValidationError('[checkbox prompt] No selectable choices. All choices are disabled.');
29
+ }
30
+ return { first, last };
31
+ }, [items]);
32
+ const [active, setActive] = useState(bounds.first);
33
+ const [showHelpTip, setShowHelpTip] = useState(true);
34
+ const [errorMsg, setError] = useState(undefined);
35
+ useKeypress(async (key) => {
36
+ if (isEnterKey(key)) {
37
+ const selection = items.filter(isChecked);
38
+ const isValid = await validate([...selection]);
39
+ if (required && !items.some(isChecked)) {
40
+ setError('At least one choice must be selected');
41
+ }
42
+ else if (isValid === true) {
43
+ setStatus('done');
44
+ done(items.map((choice) => ({
45
+ value: choice.value,
46
+ checked: choice.checked,
47
+ })));
48
+ }
49
+ else {
50
+ setError(isValid || 'You must select a valid value');
51
+ }
52
+ }
53
+ else if (isActivateNextItemKey(key) || isActivatePreviousItemKey(key)) {
54
+ if ((isActivatePreviousItemKey(key) && active !== bounds.first) ||
55
+ (isActivateNextItemKey(key) && active !== bounds.last)) {
56
+ const offset = isUpKey(key) ? -1 : 1;
57
+ let next = active;
58
+ do {
59
+ next = (next + offset + items.length) % items.length;
60
+ } while (!isSelectable(items[next]));
61
+ setActive(next);
62
+ }
63
+ }
64
+ else if (isSpaceKey(key)) {
65
+ setError(undefined);
66
+ setItems(items.map((choice, i) => (i === active ? toggle(choice) : choice)));
67
+ }
68
+ else if (key.name === 'a') {
69
+ const selectAll = Boolean(items.find((choice) => isSelectable(choice) && !choice.checked));
70
+ setItems(items.map(check(selectAll)));
71
+ }
72
+ else if (key.name === 'i') {
73
+ setItems(items.map(toggle));
74
+ }
75
+ else if (isNumberKey(key)) {
76
+ const position = Number(key.name) - 1;
77
+ const item = items[position];
78
+ if (item != null && isSelectable(item)) {
79
+ setActive(position);
80
+ setItems(items.map((choice, i) => i === position ? toggle(choice) : choice));
81
+ }
82
+ }
83
+ else if (isMoveItemUpKey(key) || isMoveItemDownKey(key)) {
84
+ setShowHelpTip(false);
85
+ if (items.length < 2) {
86
+ return;
87
+ }
88
+ const offset = isMoveItemUpKey(key) ? -1 : 1;
89
+ let moveActiveTo = active + offset;
90
+ if (!config.sortingLoop &&
91
+ (moveActiveTo < 0 || moveActiveTo > items.length - 1)) {
92
+ return;
93
+ }
94
+ let newItems;
95
+ if (moveActiveTo === -1) {
96
+ newItems = [...items.slice(1), items[0]];
97
+ moveActiveTo = items.length - 1;
98
+ }
99
+ else if (moveActiveTo === items.length) {
100
+ newItems = [items.at(-1), ...items.slice(0, -1)];
101
+ moveActiveTo = 0;
102
+ }
103
+ else {
104
+ newItems = [...items];
105
+ newItems[moveActiveTo] = items[active];
106
+ newItems[active] = items[moveActiveTo];
107
+ }
108
+ setItems(newItems);
109
+ setActive(moveActiveTo);
110
+ }
111
+ });
112
+ const message = theme.style.message(config.message, status);
113
+ const page = usePagination({
114
+ items,
115
+ active,
116
+ renderItem({ item, isActive }) {
117
+ const line = item.name || item.value;
118
+ if (item.disabled) {
119
+ const disabledLabel = typeof item.disabled === 'string' ? item.disabled : '(disabled)';
120
+ return theme.style.disabledChoice(`${line} ${disabledLabel}`);
121
+ }
122
+ const checkbox = item.checked
123
+ ? theme.icon.checked
124
+ : theme.icon.unchecked;
125
+ const color = isActive
126
+ ? theme.style.highlight
127
+ : (x) => x;
128
+ const cursor = isActive ? theme.icon.cursor : ' ';
129
+ return color(`${cursor}${checkbox} ${line}`);
130
+ },
131
+ pageSize,
132
+ loop: false,
133
+ });
134
+ if (status === 'done') {
135
+ const selection = items.filter(isChecked);
136
+ const answer = theme.style.answer(theme.style.renderSelectedChoices(selection, items));
137
+ return `${prefix} ${message} ${answer}`;
138
+ }
139
+ let helpTipTop = '';
140
+ let helpTipBottom = '';
141
+ if (theme.helpMode === 'always' ||
142
+ (theme.helpMode === 'auto' &&
143
+ showHelpTip &&
144
+ (instructions === undefined || instructions))) {
145
+ if (typeof instructions === 'string') {
146
+ helpTipTop = instructions;
147
+ }
148
+ else {
149
+ const keys = [
150
+ `${theme.style.key('space')} to select`,
151
+ `${theme.style.key('a')} to toggle all`,
152
+ `${theme.style.key('i')} to invert selection`,
153
+ `${theme.style.key('shift+up')} to move item up`,
154
+ `${theme.style.key('shift+down')} to move item down`,
155
+ `and ${theme.style.key('enter')} to proceed`,
156
+ ];
157
+ helpTipTop = ` (Press ${keys.join(', ')})`;
158
+ }
159
+ if (items.length > pageSize &&
160
+ (theme.helpMode === 'always' ||
161
+ (theme.helpMode === 'auto' && firstRender.current))) {
162
+ helpTipBottom = `\n${theme.style.help('(Use arrow keys to reveal more choices)')}`;
163
+ firstRender.current = false;
164
+ }
165
+ }
166
+ let error = '';
167
+ if (errorMsg) {
168
+ error = `\n${theme.style.error(errorMsg)}`;
169
+ }
170
+ return `${prefix} ${message}${helpTipTop}\n${page}${helpTipBottom}${error}${ansiEscapes.cursorHide}`;
171
+ });
172
+ function isSelectable(item) {
173
+ return !item.disabled;
174
+ }
175
+ function isChecked(item) {
176
+ return isSelectable(item) && Boolean(item.checked);
177
+ }
178
+ function toggle(item) {
179
+ return isSelectable(item) ? { ...item, checked: !item.checked } : item;
180
+ }
181
+ function check(checked) {
182
+ return function (item) {
183
+ return isSelectable(item) ? { ...item, checked } : item;
184
+ };
185
+ }
186
+ function isActivatePreviousItemKey(key) {
187
+ return isUpKey(key) && !key.shift;
188
+ }
189
+ function isActivateNextItemKey(key) {
190
+ return isDownKey(key) && !key.shift;
191
+ }
192
+ function isMoveItemUpKey(key) {
193
+ return key.shift && isUpKey(key);
194
+ }
195
+ function isMoveItemDownKey(key) {
196
+ return key.shift && isDownKey(key);
197
+ }
package/index.js ADDED
@@ -0,0 +1,52 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { Command } from 'commander';
4
+ import chalk from 'chalk';
5
+ import main from './dist/index.js';
6
+
7
+ const program = new Command();
8
+
9
+ program
10
+ .name('job-queue')
11
+ .description(
12
+ 'A CLI app to keep track of jobs/tasks built around a couple of JSON files.',
13
+ )
14
+ .version('0.0.0')
15
+ .option(
16
+ '-c, --config <path>',
17
+ 'path to directory containing config.json (uses new system app dir by default)',
18
+ )
19
+ .option(
20
+ '-j, --jobqueue <path>',
21
+ 'path to jobqueue.json (uses config by default)',
22
+ )
23
+ .option(
24
+ '-p, --projectpool <path>',
25
+ 'path to projectpool.json (uses config by default)',
26
+ )
27
+ .option(
28
+ '-e, --editor <editor>',
29
+ 'name of editor to use (uses config by default or git editor, if installed)',
30
+ )
31
+ .action(async (options) => {
32
+ const configDir = options.config;
33
+ delete options.config;
34
+ [('jobqueue', 'projectpool', 'editor')].forEach((key) => {
35
+ if (!options[key] || options[key].length === 0) delete options[key];
36
+ });
37
+
38
+ await main(configDir, { ...options })
39
+ .then(() => {
40
+ console.log(chalk.cyanBright('🖖 Live long and prosper...'));
41
+ process.exit();
42
+ })
43
+ .catch((error) => {
44
+ console.log(chalk.red('An error occured:'));
45
+ console.group();
46
+ console.log(error.message || error);
47
+ console.groupEnd();
48
+ process.exit(1);
49
+ });
50
+ });
51
+
52
+ program.parse(process.argv);
package/package.json ADDED
@@ -0,0 +1,56 @@
1
+ {
2
+ "name": "@uss-stargazer/job-queue",
3
+ "version": "0.0.1",
4
+ "description": "A CLI app to keep track of jobs/tasks built around a couple of JSON files.",
5
+ "author": "uss-stargazer",
6
+ "license": "Apache-2.0",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/uss-stargazer/jobqueue.git"
10
+ },
11
+ "type": "module",
12
+ "bin": {
13
+ "job-queue": "./index.js",
14
+ "jobq": "./index.js"
15
+ },
16
+ "files": ["index.js", "dist/", "!TODO"],
17
+ "scripts": {
18
+ "start": "node ./index.js",
19
+ "clean": "rimraf coverage dist tmp",
20
+ "prebuild": "npm run lint",
21
+ "build": "tsc -p tsconfig.json",
22
+ "build:watch": "tsc -w -p tsconfig.json",
23
+ "build:release": "npm run clean && tsc -p tsconfig.release.json",
24
+ "lint": "eslint .",
25
+ "prettier": "prettier \"{src,__{tests}__}/**/*.{ts,mts}\" --config .prettierrc --write",
26
+ "prettier:check": "prettier \"{src,__{tests}__}/**/*.{ts,mts}\" --config .prettierrc --check"
27
+ },
28
+ "dependencies": {
29
+ "@inquirer/prompts": "^8.2.0",
30
+ "@inquirer/search": "^4.1.0",
31
+ "ansi-escapes": "^7.2.0",
32
+ "chalk": "^5.6.2",
33
+ "clear": "^0.1.0",
34
+ "commander": "^14.0.2",
35
+ "edit-like-git": "^1.0.2",
36
+ "env-paths": "^4.0.0",
37
+ "figlet": "^1.9.4",
38
+ "inquirer": "^13.2.0",
39
+ "tmp-promise": "^3.0.3",
40
+ "zod": "^4.3.6"
41
+ },
42
+ "devDependencies": {
43
+ "@eslint/js": "^9.39.2",
44
+ "@types/eslint__js": "^8.42.3",
45
+ "@types/node": "^25.0.6",
46
+ "@typescript-eslint/parser": "^8.52.0",
47
+ "eslint": "^9.39.2",
48
+ "eslint-config-prettier": "^10.1.8",
49
+ "globals": "^17.0.0",
50
+ "prettier": "^3.7.4",
51
+ "rimraf": "^6.1.2",
52
+ "ts-api-utils": "^2.4.0",
53
+ "typescript": "^5.9.3",
54
+ "typescript-eslint": "^8.52.0"
55
+ }
56
+ }