@waron97/prbot 2.4.0 → 2.6.0

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/README.md CHANGED
@@ -118,7 +118,7 @@ Options:
118
118
 
119
119
  ### `prbot commit`
120
120
 
121
- Interactive commit builder. Prompts for operation type (`[IMP]`, `[FIX]`, etc.), what changed (workflow, module, wizard, symphony process), and a message. If nothing is staged, shows unstaged files and lets you select which to stage first. Previews the final commit message before confirming.
121
+ Interactive commit builder. Prompts for operation type (`[IMP]`, `[FIX]`, etc.), and a message. The destinatin module will be automatically detected. If nothing is staged, shows unstaged files and lets you select which to stage first. Previews the final commit message before confirming.
122
122
 
123
123
  ```bash
124
124
  prbot commit
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@waron97/prbot",
3
- "version": "2.4.0",
3
+ "version": "2.6.0",
4
4
  "description": "",
5
5
  "main": "index.js",
6
6
  "scripts": {
@@ -13,133 +13,182 @@ const commitOperations = [
13
13
  },
14
14
  { name: `📖 DOC ${chalk.gray('- Documentation changes')}`, value: '[DOC]' },
15
15
  { name: `🩹 FIX ${chalk.gray('- Bugfix or hotfix')}`, value: '[FIX]' },
16
- { name: `🛠️ IMP ${chalk.gray('- Improvement of existing code')}`, value: '[IMP]' },
16
+ { name: `🛠️ IMP ${chalk.gray('- Improvement of existing code')}`, value: '[IMP]' },
17
17
  { name: `💬 I18N ${chalk.gray('- Translation changes')}`, value: '[I18N]' },
18
18
  { name: `📦 MIG ${chalk.gray('- Module migration')}`, value: '[MIG]' },
19
19
  { name: `🔄 REF ${chalk.gray('- Code refactoring')}`, value: '[REF]' },
20
20
  { name: `🎉 REL ${chalk.gray('- Release commit')}`, value: '[REL]' },
21
- { name: `🗑️ REM ${chalk.gray('- Removing unnecessary files')}`, value: '[REM]' },
22
- { name: `✏️ REN ${chalk.gray('- Renaming files/variables/models/etc.')}`, value: '[REN]' },
21
+ { name: `🗑️ REM ${chalk.gray('- Removing unnecessary files')}`, value: '[REM]' },
22
+ { name: `✏️ REN ${chalk.gray('- Renaming files/variables/models/etc.')}`, value: '[REN]' },
23
23
  { name: `🔙 REV ${chalk.gray('- Revert of an existing commit')}`, value: '[REV]' },
24
24
  { name: `🧳 SUB ${chalk.gray('- Submodule adding/updating')}`, value: '[SUB]' },
25
- { name: `#️⃣ VER ${chalk.gray('- Versioning')}`, value: '[VER]' },
25
+ { name: `#️⃣ VER ${chalk.gray('- Versioning')}`, value: '[VER]' },
26
26
  ];
27
27
 
28
- const commitTypes = [
29
- { name: '🔧 Workflow', value: 'workflow' },
30
- { name: '📋 Module', value: 'module' },
31
- { name: '👤 Wizard', value: 'wizard' },
32
- { name: '⚙️ Symphony Process', value: 'symphony' },
33
- ];
28
+ function getModuleFromFile(file) {
29
+ const parts = file.split('/');
34
30
 
35
- async function commit() {
36
- const ADDONS_PATH = resolveAddonsPath(process.env.ADDONS_PATH);
31
+ if (parts[0] === 'config') {
32
+ return parts[1];
33
+ }
37
34
 
38
- const unstagedChanges = await execGit(['diff', '--name-only'], ADDONS_PATH);
39
- const stagedChanges = await execGit(['diff', '--cached', '--name-only'], ADDONS_PATH);
35
+ if (parts[0] === '.cloudbuild') {
36
+ const allIndex = parts.indexOf('all');
40
37
 
41
- let stageFilesAnswers = [];
38
+ if (allIndex !== -1) {
39
+ return parts.slice(0, allIndex + 1).join('/');
40
+ }
41
+ }
42
+
43
+ return parts[0];
44
+ }
42
45
 
43
- if (!stagedChanges.trim()) {
46
+ function validateSameModule(files) {
47
+ const modules = files.map(getModuleFromFile);
48
+ const currentModule = `[${modules[0]}]`;
49
+
50
+ const allSameModule = modules.every((module) => `[${module}]` === currentModule);
51
+
52
+ if (!allSameModule) {
53
+ console.log(chalk.red('Selected files are not of the same module'));
54
+ return null;
55
+ }
56
+
57
+ return currentModule;
58
+ }
59
+
60
+ async function getFilesToCommit(stagedChanges, unstagedChanges) {
61
+ if (stagedChanges.trim()) {
62
+ console.log(chalk.green('Staged changes:'));
63
+ console.log(stagedChanges);
64
+
65
+ return {
66
+ filesToCheck: stagedChanges.trim().split('\n'),
67
+ filesToStage: [],
68
+ };
69
+ }
70
+
71
+ const unstagedFiles = unstagedChanges.trim().split('\n');
72
+
73
+ while (true) {
44
74
  console.log(chalk.yellow('No staged changes found.'));
45
75
  console.log(chalk.yellow('Unstaged changes:'));
46
76
  console.log(unstagedChanges);
47
77
 
48
- stageFilesAnswers = await inquirer.prompt([
78
+ const answers = await inquirer.prompt([
49
79
  {
50
80
  message: 'Select unstaged files to stage for commit:',
51
81
  type: 'checkbox',
52
82
  name: 'filesToStage',
53
- choices: unstagedChanges
54
- .trim()
55
- .split('\n')
56
- .map((file) => file),
83
+ choices: unstagedFiles,
57
84
  },
58
85
  ]);
59
- } else {
60
- console.log(chalk.green('Staged changes:'));
61
- console.log(stagedChanges);
86
+
87
+ const currentModule = validateSameModule(answers.filesToStage);
88
+
89
+ if (currentModule) {
90
+ return {
91
+ filesToCheck: answers.filesToStage,
92
+ filesToStage: answers.filesToStage,
93
+ currentModule,
94
+ };
95
+ }
62
96
  }
97
+ }
63
98
 
64
- const answers = await inquirer.prompt([
65
- {
66
- type: 'search-list',
67
- message: 'Select an operation:',
68
- name: 'commitOperation',
69
- choices: commitOperations,
70
- },
71
- {
72
- type: 'search-list',
73
- message: 'Select what has been changed:',
74
- name: 'commitType',
75
- choices: commitTypes,
76
- when(answers) {
77
- return answers.commitOperation !== '[DOC]';
78
- },
79
- },
80
- {
81
- type: 'input',
82
- message(answers) {
83
- return `Please enter the name of the ${answers.commitType}:`;
99
+ async function commit() {
100
+ const ADDONS_PATH = resolveAddonsPath(process.env.ADDONS_PATH);
101
+
102
+ while (true) {
103
+ const unstagedChanges = await execGit(['diff', '--name-only'], ADDONS_PATH);
104
+ const stagedChanges = await execGit(['diff', '--cached', '--name-only'], ADDONS_PATH);
105
+
106
+ if (!unstagedChanges.trim() && !stagedChanges.trim()) {
107
+ console.log(chalk.red('No changes found to commit.'));
108
+ return;
109
+ }
110
+
111
+ const {
112
+ filesToCheck,
113
+ filesToStage,
114
+ currentModule: selectedModule,
115
+ } = await getFilesToCommit(stagedChanges, unstagedChanges);
116
+
117
+ if (filesToCheck.length === 0) {
118
+ console.log(chalk.red('No files selected.'));
119
+ return;
120
+ }
121
+
122
+ let currentModule = selectedModule || validateSameModule(filesToCheck);
123
+
124
+ if (!currentModule) {
125
+ return;
126
+ }
127
+
128
+ const answers = await inquirer.prompt([
129
+ {
130
+ type: 'search-list',
131
+ message: 'Select an operation:',
132
+ name: 'commitOperation',
133
+ choices: commitOperations,
84
134
  },
85
- name: 'commitModule',
86
- default: 'config_wf_',
87
- when(answers) {
88
- return answers.commitType === 'workflow' || answers.commitType === 'module';
135
+ {
136
+ type: 'input',
137
+ message: 'Please enter your message:',
138
+ name: 'commitMessage',
139
+ filter: (input) => input.trim(),
140
+ when(answers) {
141
+ return answers.commitOperation !== '[DOC]';
142
+ },
89
143
  },
90
- filter(input) {
91
- let value = input.trim();
144
+ ]);
92
145
 
93
- if (!value.startsWith('[')) {
94
- value = `[${value}`;
95
- }
146
+ if (answers.commitOperation === '[DOC]') {
147
+ currentModule = '[CHANGELOG]';
148
+ answers.commitMessage = 'Changelog';
149
+ }
96
150
 
97
- if (!value.endsWith(']')) {
98
- value = `${value}]`;
99
- }
151
+ const commitMessage = `${answers.commitOperation}${currentModule} ${answers.commitMessage}`;
100
152
 
101
- return value;
102
- },
103
- },
104
- {
105
- type: 'input',
106
- message: 'Please enter your message:',
107
- name: 'commitMessage',
108
- filter: (input) => input.trim(),
109
- when(answers) {
110
- return answers.commitOperation !== '[DOC]';
153
+ const finalPrompt = await inquirer.prompt([
154
+ {
155
+ type: 'confirm',
156
+ message: `${chalk.red(commitMessage)}\nDo you want to proceed with this commit message?`,
157
+ name: 'confirmCommit',
111
158
  },
112
- },
113
- ]);
159
+ ]);
114
160
 
115
- if (answers.commitOperation === '[DOC]') {
116
- answers.commitModule = '[CHANGELOG]';
117
- answers.commitMessage = 'Changelog';
118
- }
161
+ if (!finalPrompt.confirmCommit) {
162
+ return;
163
+ }
119
164
 
120
- if (answers.commitType === 'wizard') {
121
- answers.commitModule = '[.cloudbuild/pb/B2WA/processes/all]';
122
- }
165
+ if (filesToStage.length > 0) {
166
+ await execGit(['add', ...filesToStage], ADDONS_PATH);
167
+ }
123
168
 
124
- if (answers.commitType === 'symphony') {
125
- answers.commitModule = '[.cloudbuild/symphony/B2WA/processes/all]';
126
- }
169
+ await execGit(['commit', '-m', commitMessage], ADDONS_PATH);
170
+ console.log(chalk.green('Commit created successfully!'));
127
171
 
128
- const commitMessage = `${answers.commitOperation}${answers.commitModule} ${answers.commitMessage}`;
172
+ const remainingUnstaged = await execGit(['diff', '--name-only'], ADDONS_PATH);
173
+ const remainingStaged = await execGit(['diff', '--cached', '--name-only'], ADDONS_PATH);
129
174
 
130
- const finalPrompt = await inquirer.prompt([
131
- {
132
- type: 'confirm',
133
- message: `${chalk.red(commitMessage)}\nDo you want to proceed with this commit message?`,
134
- name: 'confirmCommit',
135
- },
136
- ]);
175
+ if (!remainingUnstaged.trim() && !remainingStaged.trim()) {
176
+ console.log(chalk.green('No more changes to commit.'));
177
+ break;
178
+ }
137
179
 
138
- if (finalPrompt.confirmCommit) {
139
- if (stageFilesAnswers.filesToStage && stageFilesAnswers.filesToStage.length > 0) {
140
- await execGit(['add', ...stageFilesAnswers.filesToStage], ADDONS_PATH);
180
+ const { continueCommit } = await inquirer.prompt([
181
+ {
182
+ type: 'confirm',
183
+ name: 'continueCommit',
184
+ message: 'Do you want to create another commit?',
185
+ default: true,
186
+ },
187
+ ]);
188
+
189
+ if (!continueCommit) {
190
+ break;
141
191
  }
142
- await execGit(['commit', '-m', commitMessage], ADDONS_PATH);
143
192
  }
144
193
  }
145
194
 
@@ -1,8 +1,9 @@
1
1
  import { exportPb } from './exportPb.js';
2
2
  import { exportImperex } from './exportImperex.js';
3
+ import { exportEmailTemplates } from './exportEmailTemplates.js';
3
4
 
4
5
  function exportRip() {
5
6
  console.log('Not implemented yet.');
6
7
  }
7
8
 
8
- export { exportPb, exportRip, exportImperex };
9
+ export { exportPb, exportRip, exportImperex, exportEmailTemplates };
@@ -0,0 +1,142 @@
1
+ import fs from 'fs/promises';
2
+ import path from 'path';
3
+ import fetch from 'node-fetch';
4
+ import search from '@inquirer/search';
5
+ import { getToken } from '../lib/auth.js';
6
+ import { execGit } from '../lib/git.js';
7
+ import { resolveAddonsPath } from '../lib/addons.js';
8
+ import { fuzzyMatch } from '../lib/fuzzy.js';
9
+
10
+ async function getWorkflows(token) {
11
+ const url = `${process.env.RIP_URL}/symple.workflow/*`;
12
+ const response = await fetch(url, {
13
+ headers: { Authorization: `Bearer ${token}` },
14
+ });
15
+ if (!response.ok) throw new Error(await response.text());
16
+ return await response.json();
17
+ }
18
+
19
+ async function getEmailTemplates(workflowId, token) {
20
+ const url = `${process.env.RIP_URL}/symple.workflow/get_email_templates`;
21
+ const response = await fetch(url, {
22
+ method: 'POST',
23
+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
24
+ body: JSON.stringify({ workflow_id: workflowId }),
25
+ });
26
+ if (!response.ok) throw new Error(await response.text());
27
+ return await response.json();
28
+ }
29
+
30
+ const VOID_ELEMENTS = /^(area|base|br|col|embed|hr|img|input|link|meta|param|source|track|wbr)$/i;
31
+
32
+ function sanitizeBodyHtml(html) {
33
+ // Convert bare void-element tags to self-closing so the XML stays valid.
34
+ // Also replace   which is not a predefined XML entity.
35
+ return html
36
+ .replace(/ /g, ' ')
37
+ .replace(/<([a-zA-Z]+)(\s[^>]*[^/]|[^/>]*)>/g, (match, tag, attrs) => {
38
+ if (!VOID_ELEMENTS.test(tag)) return match;
39
+ return `<${tag}${attrs ?? ''}/>`;
40
+ });
41
+ }
42
+
43
+ function toXmlId(name) {
44
+ return name.replace(/[^a-zA-Z0-9]+/g, '_').replace(/^_+|_+$/g, '');
45
+ }
46
+
47
+ function escapeXml(str) {
48
+ return String(str ?? '')
49
+ .replace(/&/g, '&amp;')
50
+ .replace(/</g, '&lt;')
51
+ .replace(/>/g, '&gt;')
52
+ .replace(/"/g, '&quot;');
53
+ }
54
+
55
+ function generateXml(templates) {
56
+ const records = templates
57
+ .map((t) => {
58
+ const id = toXmlId(t.name);
59
+ const modelRef = Object.values(t.model_id)[0];
60
+ return ` <record id="${id}" model="mail.template">
61
+ <field name="name">${escapeXml(t.name)}</field>
62
+ <field name="model_id" ref="${modelRef}"/>
63
+ <field name="template_code">${escapeXml(t.template_code)}</field>
64
+ <field name="subject">${escapeXml(t.subject)}</field>
65
+ <field name="email_from">${escapeXml(t.email_from)}</field>
66
+ <field name="email_to">${escapeXml(t.email_to)}</field>
67
+ <field name="body_html" type="html">
68
+ ${sanitizeBodyHtml(t.body_html)}
69
+ </field>
70
+ </record>`;
71
+ })
72
+ .join('\n');
73
+
74
+ return `<?xml version="1.0" encoding="utf-8"?>
75
+ <odoo>
76
+ <data noupdate="1">
77
+ ${records}
78
+ </data>
79
+ </odoo>
80
+ `;
81
+ }
82
+
83
+ async function getModuleChoices() {
84
+ const ADDONS_PATH = resolveAddonsPath(process.env.ADDONS_PATH);
85
+ const configDir = path.join(ADDONS_PATH, 'config');
86
+ const entries = await fs.readdir(configDir, { withFileTypes: true });
87
+ return entries
88
+ .filter((e) => e.isDirectory())
89
+ .map((e) => ({ name: e.name, value: e.name }));
90
+ }
91
+
92
+ async function exportEmailTemplates(opts) {
93
+ const token = await getToken();
94
+
95
+ const moduleChoices = await getModuleChoices();
96
+ const module = await search({
97
+ message: 'Select module:',
98
+ source: async (input) => {
99
+ if (!input) return moduleChoices;
100
+ return moduleChoices.filter((c) => fuzzyMatch(c.name, input));
101
+ },
102
+ });
103
+
104
+ console.log('Fetching workflows...');
105
+ const workflows = await getWorkflows(token);
106
+ const choices = workflows.map((w) => ({ name: w.name, value: w.id }));
107
+
108
+ const workflowId = await search({
109
+ message: 'Select workflow:',
110
+ source: async (input) => {
111
+ if (!input) return choices;
112
+ return choices.filter((c) => fuzzyMatch(c.name, input));
113
+ },
114
+ });
115
+
116
+ console.log(`Fetching email templates for workflow ${workflowId}...`);
117
+ const templates = await getEmailTemplates(workflowId, token);
118
+
119
+ if (!templates.length) {
120
+ console.log('No email templates found for this workflow.');
121
+ return;
122
+ }
123
+
124
+ const ADDONS_PATH = resolveAddonsPath(process.env.ADDONS_PATH);
125
+ const dataDir = path.join(ADDONS_PATH, 'config', module, 'data');
126
+ await fs.mkdir(dataDir, { recursive: true });
127
+
128
+ const outPath = path.join(dataDir, 'mail_templates.xml');
129
+ await fs.writeFile(outPath, generateXml(templates), 'utf-8');
130
+ console.log(`Written: ${outPath}`);
131
+
132
+ if (opts.commit !== false) {
133
+ await execGit(['add', outPath], ADDONS_PATH);
134
+ await execGit(
135
+ ['commit', '-m', `[IMP][${module}] Export email templates`],
136
+ ADDONS_PATH,
137
+ );
138
+ console.log('Committed.');
139
+ }
140
+ }
141
+
142
+ export { exportEmailTemplates };
package/src/index.js CHANGED
@@ -8,34 +8,51 @@ import omelette from 'omelette';
8
8
  import { autopr } from './commands/autopr.js';
9
9
  import { changelog } from './commands/changelog.js';
10
10
  import { commit } from './commands/commit.js';
11
- import { exportPb, exportRip, exportImperex } from './commands/export.js';
11
+ import { exportPb, exportRip, exportImperex, exportEmailTemplates } from './commands/export.js';
12
12
  import { init } from './commands/init.js';
13
13
  import { main as prMain } from './commands/pr.js';
14
14
  import { verbot } from './commands/ver.js';
15
15
  import { CONFIG_FILE } from './config.js';
16
16
 
17
- const completion = omelette('prbot <command> <module>');
18
- completion.on('command', ({ reply }) => {
19
- reply(['pr', 'ver', 'init', 'changelog', 'autopr', 'commit']);
20
- });
17
+ const EXPORT_SUBCOMMANDS = ['workflow', 'email-templates', 'pb', 'imperex', 'rip'];
21
18
 
22
- completion.on('module', ({ before, reply }) => {
23
- if (['init', 'changelog', 'autopr'].includes(before)) {
24
- reply([]);
25
- return;
26
- }
19
+ function replyModules(reply) {
27
20
  try {
28
21
  const raw = readFileSync(CONFIG_FILE, 'utf-8');
29
22
  const match = raw.match(/^ADDONS_PATH=(.+)$/m);
30
- if (!match) {
31
- reply([]);
32
- return;
33
- }
23
+ if (!match) { reply([]); return; }
34
24
  const addonsPath = match[1].trim().replace(/^~/, process.env.HOME || '');
35
25
  reply(readdirSync(path.join(addonsPath, 'config')));
36
26
  } catch {
37
27
  reply([]);
38
28
  }
29
+ }
30
+
31
+ const completion = omelette('prbot <command> <subOrModule> <module>');
32
+ completion.on('command', ({ reply }) => {
33
+ reply(['pr', 'ver', 'init', 'changelog', 'autopr', 'commit', 'export']);
34
+ });
35
+
36
+ // 2nd token: export subcommands or module (for non-export commands)
37
+ completion.on('subOrModule', ({ before, reply }) => {
38
+ if (before === 'export') {
39
+ reply(EXPORT_SUBCOMMANDS);
40
+ return;
41
+ }
42
+ if (['init', 'changelog', 'autopr'].includes(before)) {
43
+ reply([]);
44
+ return;
45
+ }
46
+ replyModules(reply);
47
+ });
48
+
49
+ // 3rd token: module (only relevant for export subcommands that take one)
50
+ completion.on('module', ({ before, reply }) => {
51
+ if (['workflow'].includes(before)) {
52
+ replyModules(reply);
53
+ } else {
54
+ reply([]);
55
+ }
39
56
  });
40
57
 
41
58
  completion.init();
@@ -147,6 +164,15 @@ exportCmd
147
164
  });
148
165
  });
149
166
 
167
+ exportCmd
168
+ .command('email-templates')
169
+ .option('--no-commit')
170
+ .action((opts) => {
171
+ exportEmailTemplates(opts).catch((err) => {
172
+ throw err;
173
+ });
174
+ });
175
+
150
176
  program.command('update').action(() => {
151
177
  console.log('Updating prbot...');
152
178
  execFile('npm', ['i', '-g', '@waron97/prbot'], (error, stdout, stderr) => {