0

I want to write a code generation tool in dart for generating keys and trnaslation values in .dart files from json files.

I tried this

in lib/sample_console.dart

library sample_console;

import 'package:build/build.dart';

import 'sample_console.dart';

export 'src/sample_console_base.dart';

Builder sampleConsoleBuilder(BuilderOptions options) {
  print(options.config); // I believe the argument is passed here
                         // but I can't see it in the output
  return SampleConsoleBuilder(options);
}

in lib/src/sample_console_base.dart

import 'dart:convert';

import 'package:build/build.dart';

class SampleConsoleBuilder extends Builder {
  BuilderOptions config;

  SampleConsoleBuilder(this.config);

  @override
  Future build(BuildStep buildStep) async {
    // Retrieve the currently matched asset
    AssetId inputId = buildStep.inputId;

    // Create a new target `AssetId` based on the current one
    AssetId keys = inputId.changeExtension('_keys.g.dart');
    String contents = await buildStep.readAsString(inputId);

    Map<String, dynamic> json = jsonDecode(contents);

    String output = '''''';

    json.keys.forEach((key) {
      output += "class $key {";
      json[key].keys.forEach((key2) {
        output += "\n  static const String $key2 = '$key.$key2';";
      });
      output += "\n}\n\n";
    });

    // Write out the new asset
    await buildStep.writeAsString(keys, '''
/* 
---
This is a generated file at ${DateTime.now()}
---
*/
// OUTPUT: 
$output

// config
// ${config.config}
''');
  }

  @override
  Map<String, List<String>> get buildExtensions => {
        '.json': ['_keys.g.dart']
      };
}

the input is lib/translations/en.json

{
  "GENERAL": {
    "ENABLED": "Enabled"
  },
  "GENERAL_FORM": {
    "ENABLED": "General Form Enabled"
  }
}

the output is lib/translations/en_keys.g.dart

/* 
---
This is a generated file at 2022-11-29 16:09:12.051350
---
*/
// OUTPUT: 
class GENERAL {
  static const String ENABLED = 'GENERAL.ENABLED';
}

class GENERAL_FORM {
  static const String ENABLED = 'GENERAL_FORM.ENABLED';
}

// config
// {}

now I don't want to generate multiple *_keys.g.dart file for multiple *.json files I only want one keys file like translation_keys.g.dart (I don't know how to do this) but I want to have multiple values file en_values.g.dart (but I know how to do this. since it runs for every file by default I can do this)

also I want to get input file and export dirrectory (to save the files from the user I want to get it from user when they run this command: dart run build_runner build some-1 some-2 I want that some-1 as input dir and some-2 as output dir.

Thanks in advance ^^

0 Answers0