Skip to content

Commit

Permalink
initial migration
Browse files Browse the repository at this point in the history
  • Loading branch information
ItshMoh committed Sep 21, 2024
1 parent c69347f commit b9317b7
Show file tree
Hide file tree
Showing 15 changed files with 212 additions and 137 deletions.
48 changes: 48 additions & 0 deletions components/model-class.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
function modelClass(name, properties, required, indentLevel) {
const className = upperFirst(name);
const indent1 = indent(indentLevel);
const indent2 = indent(indentLevel + 1);
const indent3 = indent(indentLevel + 2);
const indent4 = indent(indentLevel + 3);

let output = `${indent1}class ${className}(Entity):\n`;

// Render nested classes and enums
for (const [propName, prop] of Object.entries(properties)) {
const typeInfo = getTypeInfo([propName, prop]);
if (typeInfo.recursive) {
output += modelClass(typeInfo.innerType, typeInfo.properties, prop.required(), indentLevel + 1);
} else if (typeInfo.generalType === 'enum') {
output += `${indent2}class ${typeInfo.type}(str, Enum):\n`;
for (const v of typeInfo.enum) {
output += `${indent3}${v} = '${v}'\n`;
}
}
}

// Render __init__ method
output += `${indent2}def __init__(\n`;
output += `${indent4}self`;

for (const [propName, prop] of Object.entries(properties)) {
const typeInfo = getTypeInfo([propName, prop]);
output += `,\n${indent4}${typeInfo.pythonName}${typeInfo.pythonType ? ': ' + typeInfo.pythonType : ''}`;
}
output += '\n' + indent2 + '):\n';

// Render __init__ body
const initBody = Object.entries(properties).map(([propName, prop]) => {
const typeInfo = getTypeInfo([propName, prop]);
return `${indent3}self.${typeInfo.pythonName} = ${typeInfo.pythonName}`;
});

if (initBody.length > 0) {
output += initBody.join('\n') + '\n';
} else {
output += indent3 + 'pass\n';
}

return output;
}

module.exports = modelClass;
2 changes: 2 additions & 0 deletions filters/all.js → helpers/all.js
Original file line number Diff line number Diff line change
Expand Up @@ -435,3 +435,5 @@ function getTopicInfo(channelName, channel) {
function indent(numTabs) {
return " ".repeat(numTabs * 4);
}

module.exports = filter;
15 changes: 15 additions & 0 deletions helpers/utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
const sanitizeFilename = require('sanitize-filename');

function convertToFilename(string, options = { replacement: '-', maxLength: 255 }) {
let sanitizedString = sanitizeFilename(string);

sanitizedString = sanitizedString.replace(/[\s]+/g, options.replacement);

if (sanitizedString.length > options.maxLength) {
sanitizedString = sanitizedString.slice(0, options.maxLength);
}

return sanitizedString;
}

module.exports = convertToFilename;
2 changes: 1 addition & 1 deletion lib/templateUtil.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// This contains functions taht are common to both the all.js filter and the post-process.js hook.
var _ = require('lodash');
const _ = require('lodash');

class TemplateUtil {

Expand Down
35 changes: 0 additions & 35 deletions partials/model-class

This file was deleted.

7 changes: 0 additions & 7 deletions template/$$schema$$.py

This file was deleted.

6 changes: 0 additions & 6 deletions template/README.md

This file was deleted.

15 changes: 15 additions & 0 deletions template/README.md.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
const { File } = require('@asyncapi/generator-react-sdk');

function ReadmeFile({ asyncapi }) {
return (
<File name={'README.md'}>
{`# ${ asyncapi.info().title() }
## Version ${ asyncapi.info().version() }
${ asyncapi.info().description() }`}
</File>
);
}

module.exports = ReadmeFile;
16 changes: 16 additions & 0 deletions template/config-template.in.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
const { File } = require('@asyncapi/generator-react-sdk');

function ReadmeFile({ asyncapi }) {
return (
<File name={'config-template.in'}>
{`[DEFAULT]
host=
password=
port=
username=
`}
</File>
);
}

module.exports = ReadmeFile;
5 changes: 0 additions & 5 deletions template/config-template.ini

This file was deleted.

15 changes: 13 additions & 2 deletions template/entity.py → template/entity.py.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,23 @@
import json
const { File } = require('@asyncapi/generator-react-sdk');

function ReadmeFile({ asyncapi }) {
return (
<File name={'entity.py'}>
{`import json
class Entity():
"""This is the base class for the model classes. It provides json serialization methods."""
@classmethod
def from_json(cls, data):
jsonObj = json.loads(data)
return cls(**jsonObj)
def to_json(self):
return json.dumps(self, default=lambda o: o.__dict__, sort_keys=True, indent=2)
return json.dumps(self, default=lambda o: o.__dict__, sort_keys=True, indent=2)`}
</File>
);
}

module.exports = ReadmeFile;
70 changes: 0 additions & 70 deletions template/main.py

This file was deleted.

90 changes: 90 additions & 0 deletions template/main.py.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
const { File } = require('@asyncapi/generator-react-sdk');
const _ = require('lodash');
const { getRealSubscriber } = require('../helpers/all.js')
const {getFunctionNameByChannel } = require('../helpers/all.js')
const {getPayloadClass }= require('../helpers/all.js')
const {getFirstPublisherMessenger } = require('../helpers/all.js')
const {getMessengers } = require('../helpers/all.js')

function generatePythonCode(asyncapi, params) {
let code = `#!/usr/bin/env python3
import configparser
import logging
import time
import messaging
`;

if (asyncapi.components() && asyncapi.components().schemas()) {
Object.entries(asyncapi.components().schemas()).forEach(([schemaName, schema]) => {
const moduleName = _.lowerFirst(schemaName);
code += `from ${moduleName} import ${_.upperFirst(schemaName)}\n`;
});
} else {
code += 'from payload import Payload\n';
}

code += `
# Config has the connection properties.
def getConfig():
configParser = configparser.ConfigParser()
configParser.read('config.ini')
config = configParser['DEFAULT']
return config
`;



code += `
def main():
logging.basicConfig(level=logging.INFO)
logging.info('Start of main.')
config = getConfig()
`;

// const publishMessenger = getFirstPublisherMessenger(params, asyncapi);
// const messengers = getMessengers(params, asyncapi);

// messengers.forEach(messenger => {
// if (messenger.subscribeTopic) {
// code += ` ${messenger.name} = messaging.Messaging(config, '${messenger.subscribeTopic}', ${messenger.functionName})\n`;
// } else {
// code += ` ${messenger.name} = messaging.Messaging(config)\n`;
// }

// if (publishMessenger) {
// code += ` ${messenger.name}.loop_start()\n`;
// } else {
// code += ` ${messenger.name}.loop_forever()\n`;
// }
// });

// if (publishMessenger) {
// code += `
// # Example of how to publish a message. You will have to add arguments to the constructor on the next line:
// payload = ${publishMessenger.payloadClass}()
// payloadJson = payload.to_json()
// while True:
// ${publishMessenger.name}.publish('${publishMessenger.publishTopic}', payloadJson)
// time.sleep(1)
// `;
// }

return code;
}

function MainFile({ asyncapi, params }) {
const generatedCode = generatePythonCode(asyncapi, params);
// const allChannels = channels.all()
console.log("HIIII",asyncapi.channels())
console.log("typeof",typeof asyncapi.channels())


return (
<File name="main.py">
{generatedCode}
{/* {`heello from msin`} */}
</File>
);
}

module.exports = MainFile
13 changes: 12 additions & 1 deletion template/messaging.py → template/messaging.py.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import paho.mqtt.client as mqtt
const { File } = require('@asyncapi/generator-react-sdk');

function MessagingFile({ }) {
return (
<File name={'messaging.py'}>
{`import paho.mqtt.client as mqtt
import configparser
import logging
import json
Expand Down Expand Up @@ -58,3 +63,9 @@ def on_connect(client, userdata, flags, rc):
if (userdata):
client.subscribe(userdata)
`}
</File>
);
}

module.exports = MessagingFile;
10 changes: 0 additions & 10 deletions template/payload.py

This file was deleted.

0 comments on commit b9317b7

Please sign in to comment.