CodeWriter.ts 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. import { System } from 'csharp';
  2. import { format } from 'format';
  3. interface ICodeWriterConfig {
  4. blockStart?: string;
  5. blockEnd?: string;
  6. blockFromNewLine?: boolean;
  7. usingTabs?: boolean;
  8. endOfLine?: string;
  9. fileMark?: string;
  10. }
  11. export default class CodeWriter {
  12. private blockStart: string;
  13. private blockEnd: string;
  14. private blockFromNewLine: boolean;
  15. private indentStr: string;
  16. private endOfLine: string;
  17. private lines: Array<string>;
  18. private indent: number;
  19. private fileMark: string;
  20. public constructor(config?: ICodeWriterConfig) {
  21. config = config || {};
  22. this.blockStart = config.blockStart || '{';
  23. this.blockEnd = config.blockEnd || '}';
  24. this.blockFromNewLine = config.blockFromNewLine != undefined ? config.blockFromNewLine : true;
  25. if (config.usingTabs)
  26. this.indentStr = '\t';
  27. else
  28. this.indentStr = ' ';
  29. this.endOfLine = config.endOfLine || '\n';
  30. this.fileMark = config.fileMark ||
  31. '/** This is an automatically generated class by FairyGUI. Please do not modify it. **/';
  32. this.lines = [];
  33. this.indent = 0;
  34. this.writeMark();
  35. }
  36. public writeMark(): void {
  37. this.lines.push(this.fileMark, '');
  38. }
  39. public writeln(fmt?: string, ...args: any[]): CodeWriter {
  40. if (!fmt) {
  41. this.lines.push('');
  42. return;
  43. }
  44. let str: string = '';
  45. for (let i: number = 0; i < this.indent; i++) {
  46. str += this.indentStr;
  47. }
  48. str += format(fmt, ...args);
  49. this.lines.push(str);
  50. return this;
  51. }
  52. public startBlock(): CodeWriter {
  53. if (this.blockFromNewLine || this.lines.length == 0)
  54. this.writeln(this.blockStart);
  55. else {
  56. let str = this.lines[this.lines.length - 1];
  57. this.lines[this.lines.length - 1] = str + ' ' + this.blockStart;
  58. }
  59. this.indent++;
  60. return this;
  61. }
  62. public endBlock(): CodeWriter {
  63. this.indent--;
  64. this.writeln(this.blockEnd);
  65. return this;
  66. }
  67. public incIndent(): CodeWriter {
  68. this.indent++;
  69. return this;
  70. }
  71. public decIndent(): CodeWriter {
  72. this.indent--;
  73. return this;
  74. }
  75. public reset(): void {
  76. this.lines.length = 0;
  77. this.indent = 0;
  78. this.writeMark();
  79. }
  80. public toString(): string {
  81. return this.lines.join(this.endOfLine);
  82. }
  83. public save(filePath: string): void {
  84. let str = this.toString();
  85. System.IO.File.WriteAllText(filePath, str);
  86. }
  87. }