Create script to extract 3GPP yang modules
[scp/oam/modeling.git] / data-model / tools / extractYangFrom3gpp / 3gpp-ts-28.541 / src / js / extractYang.js
1 ////////////////////////////////////////////////////////////////////////////////
2 //
3 // Copyright 2019 highstreet technologies GmbH and others...
4 //
5 // Licensed under the Apache License, Version 2.0 (the "License");
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
8 //
9 //     http://www.apache.org/licenses/LICENSE-2.0
10 //
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
16 //
17
18 const fs = require('fs');
19 const args = process.argv.slice(2);
20 const inputFile = __dirname + '/../../' + args[0];
21 const target = __dirname + '/../../target';
22
23 const deleteFolderRecursive = function(path) {
24   if (fs.existsSync(path)) {
25     fs.readdirSync(path).forEach(function(file, index){
26       var curPath = path + "/" + file;
27       if (fs.lstatSync(curPath).isDirectory()) { // recurse
28         deleteFolderRecursive(curPath);
29       } else { // delete file
30         fs.unlinkSync(curPath);
31       }
32     });
33     fs.rmdirSync(path);
34   }
35 };
36
37 if (!fs.existsSync(inputFile)) {
38   throw new Error(['Input file:', inputFile, 'not found!'].join(' '));
39 }
40
41 if (fs.existsSync(target)) {
42   // clean
43   deleteFolderRecursive(target);
44 }
45
46
47 // start
48 fs.mkdirSync(target, { recursive: true });
49 fs.readFile(inputFile, "utf8", function (err, data) {
50   if (err) {
51     return console.log(err);
52   }
53
54   var collect = false;
55   var file = [];
56   var filename = target + '/';
57
58   var modules = data.split(/\r?\n/).forEach(function (line) {
59
60     if (line.startsWith("submodule ") || line.startsWith("module ")) {
61       collect = true;
62       filename = target + "/" + line.split(' ')[1] + '.yang';
63       file = [];
64     }
65     if (collect === true) {
66       file.push(line);
67     }
68     if (line.startsWith("}")) {
69       collect = false;
70       fs.writeFile(filename, file.join("\n"), function (err) {
71         if (err) {
72           return console.log(err);
73         }
74         console.log(["The file", filename, "was saved!"].join(' '));
75       });
76     }
77   });
78 });