utils.ts 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. /*---------------------------------------------------------------------------------------------
  2. * Copyright (c) Microsoft Corporation. All rights reserved.
  3. * Licensed under the MIT License. See License.txt in the project root for license information.
  4. *--------------------------------------------------------------------------------------------*/
  5. import * as fs from 'fs';
  6. import * as path from 'path';
  7. import * as cp from 'child_process';
  8. import * as esbuild from 'esbuild';
  9. import alias from 'esbuild-plugin-alias';
  10. import * as glob from 'glob';
  11. import { ensureDir } from './fs';
  12. export const REPO_ROOT = path.join(__dirname, '../');
  13. /**
  14. * Launch the typescript compiler synchronously over a project.
  15. */
  16. export function runTsc(_projectPath: string) {
  17. const projectPath = path.join(REPO_ROOT, _projectPath);
  18. console.log(`Launching compiler at ${_projectPath}...`);
  19. const res = cp.spawnSync(
  20. process.execPath,
  21. [path.join(__dirname, '../node_modules/typescript/lib/tsc.js'), '-p', projectPath],
  22. { stdio: 'inherit' }
  23. );
  24. console.log(`Compiled ${_projectPath}`);
  25. if (res.status !== 0) {
  26. process.exit(res.status);
  27. }
  28. }
  29. /**
  30. * Launch prettier on a specific file.
  31. */
  32. export function prettier(_filePath: string) {
  33. const filePath = path.join(REPO_ROOT, _filePath);
  34. cp.spawnSync(
  35. process.execPath,
  36. [path.join(__dirname, '../node_modules/prettier/bin-prettier.js'), '--write', filePath],
  37. { stdio: 'inherit' }
  38. );
  39. console.log(`Ran prettier over ${_filePath}`);
  40. }
  41. /**
  42. * Transform an external .d.ts file to an internal .d.ts file
  43. */
  44. export function massageAndCopyDts(source: string, destination: string, namespace: string) {
  45. const absoluteSource = path.join(REPO_ROOT, source);
  46. const absoluteDestination = path.join(REPO_ROOT, destination);
  47. const lines = fs
  48. .readFileSync(absoluteSource)
  49. .toString()
  50. .split(/\r\n|\r|\n/);
  51. let result = [
  52. `/*---------------------------------------------------------------------------------------------`,
  53. ` * Copyright (c) Microsoft Corporation. All rights reserved.`,
  54. ` * Licensed under the MIT License. See License.txt in the project root for license information.`,
  55. ` *--------------------------------------------------------------------------------------------*/`,
  56. ``,
  57. `declare namespace ${namespace} {`
  58. ];
  59. for (let line of lines) {
  60. if (/^import/.test(line)) {
  61. continue;
  62. }
  63. if (line === 'export {};') {
  64. continue;
  65. }
  66. line = line.replace(/ /g, '\t');
  67. line = line.replace(/declare /g, '');
  68. if (line.length > 0) {
  69. line = `\t${line}`;
  70. result.push(line);
  71. }
  72. }
  73. result.push(`}`);
  74. result.push(``);
  75. ensureDir(path.dirname(absoluteDestination));
  76. fs.writeFileSync(absoluteDestination, result.join('\n'));
  77. prettier(destination);
  78. }
  79. export function build(options: import('esbuild').BuildOptions) {
  80. esbuild.build(options).then((result) => {
  81. if (result.errors.length > 0) {
  82. console.error(result.errors);
  83. }
  84. if (result.warnings.length > 0) {
  85. console.error(result.warnings);
  86. }
  87. });
  88. }
  89. export function buildESM(options: { base: string; entryPoints: string[]; external: string[] }) {
  90. build({
  91. entryPoints: options.entryPoints,
  92. bundle: true,
  93. target: 'esnext',
  94. format: 'esm',
  95. drop: ['debugger'],
  96. define: {
  97. AMD: 'false'
  98. },
  99. banner: {
  100. js: bundledFileHeader
  101. },
  102. external: options.external,
  103. outbase: `src/${options.base}`,
  104. outdir: `out/languages/bundled/esm/vs/${options.base}/`,
  105. plugins: [
  106. alias({
  107. 'vscode-nls': path.join(__dirname, 'fillers/vscode-nls.ts')
  108. })
  109. ]
  110. });
  111. }
  112. function getGitVersion() {
  113. const git = path.join(REPO_ROOT, '.git');
  114. const headPath = path.join(git, 'HEAD');
  115. let head;
  116. try {
  117. head = fs.readFileSync(headPath, 'utf8').trim();
  118. } catch (e) {
  119. return void 0;
  120. }
  121. if (/^[0-9a-f]{40}$/i.test(head)) {
  122. return head;
  123. }
  124. const refMatch = /^ref: (.*)$/.exec(head);
  125. if (!refMatch) {
  126. return void 0;
  127. }
  128. const ref = refMatch[1];
  129. const refPath = path.join(git, ref);
  130. try {
  131. return fs.readFileSync(refPath, 'utf8').trim();
  132. } catch (e) {
  133. // noop
  134. }
  135. const packedRefsPath = path.join(git, 'packed-refs');
  136. let refsRaw;
  137. try {
  138. refsRaw = fs.readFileSync(packedRefsPath, 'utf8').trim();
  139. } catch (e) {
  140. return void 0;
  141. }
  142. const refsRegex = /^([0-9a-f]{40})\s+(.+)$/gm;
  143. let refsMatch;
  144. const refs = {};
  145. while ((refsMatch = refsRegex.exec(refsRaw))) {
  146. refs[refsMatch[2]] = refsMatch[1];
  147. }
  148. return refs[ref];
  149. }
  150. export const bundledFileHeader = (() => {
  151. const sha1 = getGitVersion();
  152. const semver = require('../package.json').version;
  153. const headerVersion = semver + '(' + sha1 + ')';
  154. const BUNDLED_FILE_HEADER = [
  155. '/*!-----------------------------------------------------------------------------',
  156. ' * Copyright (c) Microsoft Corporation. All rights reserved.',
  157. ' * Version: ' + headerVersion,
  158. ' * Released under the MIT license',
  159. ' * https://github.com/microsoft/monaco-editor/blob/main/LICENSE.txt',
  160. ' *-----------------------------------------------------------------------------*/',
  161. ''
  162. ].join('\n');
  163. return BUNDLED_FILE_HEADER;
  164. })();
  165. export interface IFile {
  166. path: string;
  167. contents: Buffer;
  168. }
  169. export function readFiles(
  170. pattern: string,
  171. options: { base: string; ignore?: string[]; dot?: boolean }
  172. ): IFile[] {
  173. let files = glob.sync(pattern, { cwd: REPO_ROOT, ignore: options.ignore, dot: options.dot });
  174. // remove dirs
  175. files = files.filter((file) => {
  176. const fullPath = path.join(REPO_ROOT, file);
  177. const stats = fs.statSync(fullPath);
  178. return stats.isFile();
  179. });
  180. const base = options.base;
  181. return files.map((file) => readFile(file, base));
  182. }
  183. export function readFile(file: string, base: string = '') {
  184. const baseLength = base === '' ? 0 : base.endsWith('/') ? base.length : base.length + 1;
  185. const fullPath = path.join(REPO_ROOT, file);
  186. const contents = fs.readFileSync(fullPath);
  187. const relativePath = file.substring(baseLength);
  188. return {
  189. path: relativePath,
  190. contents
  191. };
  192. }
  193. export function writeFiles(files: IFile[], dest: string) {
  194. for (const file of files) {
  195. const fullPath = path.join(REPO_ROOT, dest, file.path);
  196. ensureDir(path.dirname(fullPath));
  197. fs.writeFileSync(fullPath, file.contents);
  198. }
  199. }