Skip to content

Commit 4404b1d

Browse files
committed
feat: create local folder
1 parent bbe5bee commit 4404b1d

2 files changed

Lines changed: 99 additions & 70 deletions

File tree

solutionBuilder.js

Lines changed: 40 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,11 @@ function getBePackageConf(name, definition, branch){
8484
return {}
8585
}
8686

87-
let pip = ''
87+
let pip = "";
88+
// overide the branch if a branch is specified in the source
89+
if (definition.hasOwnProperty("branch")) {
90+
branch = definition.branch;
91+
}
8892
if (branch == 'released'){
8993
pip = definition.package + "~=" + definition.version;
9094
}else{
@@ -650,6 +654,40 @@ function transformRolesToFixture(rolesDict) {
650654
};
651655
}
652656

657+
async function createSolutionDirectory(baseDir, output)
658+
{
659+
try {
660+
// Ensure the base directory exists
661+
await fs.mkdirSync(baseDir, { recursive: true });
662+
663+
// Iterate over the output object
664+
for (const [filePath, content] of Object.entries(output)) {
665+
// Resolve the full path for the file
666+
const fullPath = path.join(baseDir, filePath);
667+
668+
// Ensure the directory for the file exists
669+
const dir = path.dirname(fullPath);
670+
await fs.mkdirSync(dir, { recursive: true });
671+
672+
// Write the file content
673+
if (fullPath.toLowerCase().endsWith('.yml') || fullPath.toLowerCase().endsWith('.yaml')) {
674+
// Stringify as YAML
675+
await fs.writeFileSync(fullPath, yaml.dump(content));
676+
} else if (fullPath.toLowerCase().endsWith('.json') ){
677+
// Stringify as JSON with formatting
678+
await fs.writeFileSync(fullPath, JSON.stringify(content, null, 2));
679+
} else {
680+
// Stringify as JSON with formatting
681+
await fs.writeFileSync(fullPath, content);
682+
}
683+
}
684+
685+
console.log(`Directory and files created successfully in ${baseDir}`);
686+
} catch (error) {
687+
console.error('Error creating directory and files:', error);
688+
throw error;
689+
}
690+
}
653691

654692
// Function to create a zip file
655693
async function createZip(data, filename) {
@@ -688,4 +726,4 @@ async function createZip(data, filename) {
688726

689727

690728

691-
module.exports = { mergeSolutions, getAbsolutePath, createZip, processSolutions };
729+
module.exports = { mergeSolutions, getAbsolutePath, createZip, processSolutions, createSolutionDirectory };

workbench.js

Lines changed: 59 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -129,24 +129,6 @@ async function ensureDistDkrRepo(branch = 'develop') {
129129
}
130130

131131

132-
// Get the paths from compose.yml
133-
function getComposeFilePaths(composePath) {
134-
const content = fs.readFileSync(composePath, 'utf8');
135-
const parsed = yaml.load(content);
136-
const paths = new Set();
137-
138-
if (parsed && parsed.include) {
139-
// Collect all paths from the "include" section in compose.yml
140-
for (const item of parsed.include) {
141-
if (item.path) {
142-
paths.add(item.path);
143-
}
144-
}
145-
}
146-
147-
return [...paths]; // Return paths as an array
148-
}
149-
150132
// Copy files defined in compose.yml from the dist-dkr repo
151133
async function copyDistDkrAssetsFromCompose(composeContent, branch = 'develop') {
152134

@@ -171,9 +153,9 @@ async function copyDistDkrAssetsFromCompose(composeContent, branch = 'develop')
171153
let fileContent = fs.readFileSync(srcPath, 'utf8');
172154

173155
// Fix YAML block strings if necessary
174-
fileContent = fixYmlBlockStrings(fileContent);
156+
fileContent = yaml.load(fileContent);
175157

176-
outputFiles[item.path] = fileContent;
158+
outputFiles[filePath] = fileContent;
177159
console.log(`✔️ Copied ${item.path} from dist-dkr`);
178160
} else {
179161
console.warn(`⚠️ File ${item.path} not found at path: ${srcPath}`);
@@ -202,78 +184,87 @@ async function copyDistDkrAssetsFromCompose(composeContent, branch = 'develop')
202184
return outputFiles;
203185
}
204186

187+
const getFormattedDate = () => {
188+
const now = new Date();
189+
const year = now.getFullYear();
190+
const month = String(now.getMonth() + 1).padStart(2, '0'); // Months are 0-based, so +1
191+
const day = String(now.getDate()).padStart(2, '0');
192+
return `${year}${month}${day}`;
193+
};
205194

206-
async function sendToExternalSolutionRepo(folderName, zipPath) {
195+
async function sendToExternalSolutionRepo(folderName, solutionFolder) {
207196
const repoUrl = 'https://github.com/openimis/solutions.git';
208-
const branchName = `solution/${folderName}`;
209-
const tempDir = path.join(__dirname, 'temp_solutions_repo');
210-
const unzipDir = path.join(__dirname, 'unzipped_output');
211-
const targetFolder = path.join(tempDir, folderName);
212-
197+
const branchName = `solution/${folderName}/${getFormattedDate()}`;
198+
const tempDir = path.join(__dirname, '.cache/temp_solutions_repo');
199+
213200
// Clean up any previous temp/unzip folder
214-
if (fs.existsSync(tempDir)) fs.rmSync(tempDir, { recursive: true });
215-
if (fs.existsSync(unzipDir)) fs.rmSync(unzipDir, { recursive: true });
216-
217-
fs.mkdirSync(unzipDir);
218-
219-
// Unzip output.zip
220-
await fs.createReadStream(zipPath)
221-
.pipe(unzipper.Extract({ path: unzipDir }))
222-
.promise();
223-
201+
if (!fs.existsSync(tempDir)){
202+
await git.clone(repoUrl, tempDir);
203+
}
224204
const git = simpleGit();
225-
226-
// Clone the repo and checkout a new branch
227-
await git.clone(repoUrl, tempDir);
228205
const gitRepo = simpleGit(tempDir);
229-
await gitRepo.checkout('develop');
230-
await gitRepo.checkoutBranch(branchName, 'develop');
206+
await gitRepo.checkout('develop'); // Clone the repo and checkout a new branch
207+
208+
const localBranches = await gitRepo.branchLocal();
209+
if(localBranches.all.includes(branchName)){
210+
await gitRepo.checkout(branchName);
211+
}else{
212+
await gitRepo.checkoutBranch(branchName, 'develop');
231213

214+
}
232215
// Create or overwrite target folder in the cloned repo
216+
const targetFolder = path.join(tempDir,folderName)
233217
if (!fs.existsSync(targetFolder)) fs.mkdirSync(targetFolder);
234-
fs.cpSync(unzipDir, targetFolder, { recursive: true });
235-
218+
fs.cpSync(solutionFolder, targetFolder, { recursive: true });
236219
// Commit and push
220+
237221
await gitRepo.add('.');
238222
await gitRepo.commit(`Add/update ${folderName} solution`);
239-
await gitRepo.push('origin', branchName);
223+
//await gitRepo.push('origin', branchName);
240224
console.log(`✔️ Pushed ${folderName} to branch ${branchName}`);
241225
}
242226

243227

244-
const { createZip, processSolutions } = require("./solutionBuilder.js");
228+
229+
230+
const { createZip, processSolutions , createSolutionDirectory} = require("./solutionBuilder.js");
245231

246232
async function main() {
247233
try {
248234
const args = process.argv.slice(2);
249235
const shouldPublish = args.includes('--publish');
250236
const folderArg = args.find(arg => arg.startsWith('--folder='));
251237
const solutionName = folderArg ? folderArg.split('=')[1] : 'default-solution';
252-
253-
const solution_path = './solution/solutions/HF.json';
238+
const solutions = {
239+
'coreMIS': './solution/solutions/coreMIS.json',
240+
'SHI': './solution/solutions/HF.json',
241+
'claimai': './solution/solutions/HF.json',
242+
'full' : './solution/solutions/full.json',
243+
}
254244
const permission = fs.readFileSync('./solution/permissions_map.json', 'utf8');
255245
const permissionMap = JSON.parse(permission);
256-
257-
258-
const output = await processSolutions(
259-
solution_path,
260-
process.cwd(),
261-
permissionMap,
262-
);
263-
264-
// Get dist-dkr files from compose.yml and merge them into output
265-
const composeFiles = await copyDistDkrAssetsFromCompose(output['compose.yml'], 'develop');
266-
Object.assign(output, composeFiles);
267-
268-
// Create zip
269-
const zipPath = path.join(__dirname, 'output.zip');
270-
await createZip(output, zipPath);
271-
272-
// Publish if requested
273-
if (shouldPublish) {
274-
await sendToExternalSolutionRepo(solutionName, zipPath);
275-
} else {
276-
console.log('🛈 Skipping publish step (use --publish to enable)');
246+
let output = []
247+
for (const [name, solution_path] of Object.entries(solutions)){
248+
console.log(`generating ${name}`)
249+
output[name] = await processSolutions(
250+
solution_path,
251+
process.cwd(),
252+
permissionMap,
253+
);
254+
// Get dist-dkr files from compose.yml and merge them into output
255+
const composeFiles = await copyDistDkrAssetsFromCompose(output[name]['compose.yml'], 'develop');
256+
Object.assign(output[name], composeFiles);
257+
const zipPath = path.join(__dirname, 'build', name +'.zip');
258+
await createZip(output[name], zipPath);
259+
baseDir = 'build/'+name
260+
await createSolutionDirectory(baseDir, output[name])
261+
262+
// Publish if requested
263+
if (shouldPublish) {
264+
await sendToExternalSolutionRepo(name, baseDir);
265+
} else {
266+
console.log('🛈 Skipping publish step (use --publish to enable)');
267+
}
277268
}
278269
} catch (error) {
279270
console.error('Error:', error);

0 commit comments

Comments
 (0)