utils.js 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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. //@ts-check
  6. const fs = require('fs');
  7. const path = require('path');
  8. const cp = require('child_process');
  9. const esbuild = require('esbuild');
  10. /** @type {any} */
  11. const alias = require('esbuild-plugin-alias');
  12. const glob = require('glob');
  13. const REPO_ROOT = path.join(__dirname, '../');
  14. exports.REPO_ROOT = REPO_ROOT;
  15. const existingDirCache = new Set();
  16. /**
  17. * @param {string} dirname
  18. */
  19. function ensureDir(dirname) {
  20. /** @type {string[]} */
  21. const dirs = [];
  22. while (dirname.length > REPO_ROOT.length) {
  23. dirs.push(dirname);
  24. dirname = path.dirname(dirname);
  25. }
  26. dirs.reverse();
  27. dirs.forEach((dir) => {
  28. if (!existingDirCache.has(dir)) {
  29. try {
  30. fs.mkdirSync(dir);
  31. } catch (err) {}
  32. existingDirCache.add(dir);
  33. }
  34. });
  35. }
  36. exports.ensureDir = ensureDir;
  37. /**
  38. * Copy a file.
  39. *
  40. * @param {string} _source
  41. * @param {string} _destination
  42. */
  43. function copyFile(_source, _destination) {
  44. const source = path.join(REPO_ROOT, _source);
  45. const destination = path.join(REPO_ROOT, _destination);
  46. ensureDir(path.dirname(destination));
  47. fs.writeFileSync(destination, fs.readFileSync(source));
  48. console.log(`Copied ${_source} to ${_destination}`);
  49. }
  50. exports.copyFile = copyFile;
  51. /**
  52. * Remove a directory and all its contents.
  53. *
  54. * @param {string} _dirPath
  55. */
  56. function removeDir(_dirPath) {
  57. const dirPath = path.join(REPO_ROOT, _dirPath);
  58. if (!fs.existsSync(dirPath)) {
  59. return;
  60. }
  61. rmDir(dirPath);
  62. console.log(`Deleted ${_dirPath}`);
  63. /**
  64. * @param {string} dirPath
  65. */
  66. function rmDir(dirPath) {
  67. const entries = fs.readdirSync(dirPath);
  68. for (const entry of entries) {
  69. const filePath = path.join(dirPath, entry);
  70. if (fs.statSync(filePath).isFile()) {
  71. fs.unlinkSync(filePath);
  72. } else {
  73. rmDir(filePath);
  74. }
  75. }
  76. fs.rmdirSync(dirPath);
  77. }
  78. }
  79. exports.removeDir = removeDir;
  80. /**
  81. * Launch the typescript compiler synchronously over a project.
  82. *
  83. * @param {string} _projectPath
  84. */
  85. function tsc(_projectPath) {
  86. const projectPath = path.join(REPO_ROOT, _projectPath);
  87. console.log(`Launching compiler at ${_projectPath}...`);
  88. cp.spawnSync(
  89. process.execPath,
  90. [path.join(__dirname, '../node_modules/typescript/lib/tsc.js'), '-p', projectPath],
  91. { stdio: 'inherit' }
  92. );
  93. console.log(`Compiled ${_projectPath}`);
  94. }
  95. exports.tsc = tsc;
  96. /**
  97. * Launch prettier on a specific file.
  98. *
  99. * @param {string} _filePath
  100. */
  101. function prettier(_filePath) {
  102. const filePath = path.join(REPO_ROOT, _filePath);
  103. cp.spawnSync(
  104. process.execPath,
  105. [path.join(__dirname, '../node_modules/prettier/bin-prettier.js'), '--write', filePath],
  106. { stdio: 'inherit' }
  107. );
  108. console.log(`Ran prettier over ${_filePath}`);
  109. }
  110. exports.prettier = prettier;
  111. /**
  112. * Transform an external .d.ts file to an internal .d.ts file
  113. *
  114. * @param {string} _source
  115. * @param {string} _destination
  116. * @param {string} namespace
  117. */
  118. function dts(_source, _destination, namespace) {
  119. const source = path.join(REPO_ROOT, _source);
  120. const destination = path.join(REPO_ROOT, _destination);
  121. const lines = fs
  122. .readFileSync(source)
  123. .toString()
  124. .split(/\r\n|\r|\n/);
  125. let result = [
  126. `/*---------------------------------------------------------------------------------------------`,
  127. ` * Copyright (c) Microsoft Corporation. All rights reserved.`,
  128. ` * Licensed under the MIT License. See License.txt in the project root for license information.`,
  129. ` *--------------------------------------------------------------------------------------------*/`,
  130. ``,
  131. `declare namespace ${namespace} {`
  132. ];
  133. for (let line of lines) {
  134. if (/^import/.test(line)) {
  135. continue;
  136. }
  137. if (line === 'export {};') {
  138. continue;
  139. }
  140. line = line.replace(/ /g, '\t');
  141. line = line.replace(/declare /g, '');
  142. if (line.length > 0) {
  143. line = `\t${line}`;
  144. result.push(line);
  145. }
  146. }
  147. result.push(`}`);
  148. result.push(``);
  149. ensureDir(path.dirname(destination));
  150. fs.writeFileSync(destination, result.join('\n'));
  151. prettier(_destination);
  152. }
  153. exports.dts = dts;
  154. /**
  155. * @param {import('esbuild').BuildOptions} options
  156. */
  157. function build(options) {
  158. esbuild.build(options).then((result) => {
  159. if (result.errors.length > 0) {
  160. console.error(result.errors);
  161. }
  162. if (result.warnings.length > 0) {
  163. console.error(result.warnings);
  164. }
  165. });
  166. }
  167. exports.build = build;
  168. /**
  169. * @param {{
  170. * base: string;
  171. * entryPoints: string[];
  172. * external: string[];
  173. * }} options
  174. */
  175. function buildESM(options) {
  176. build({
  177. entryPoints: options.entryPoints,
  178. bundle: true,
  179. target: 'esnext',
  180. format: 'esm',
  181. define: {
  182. AMD: 'false'
  183. },
  184. banner: {
  185. js: bundledFileHeader
  186. },
  187. external: options.external,
  188. outbase: `src/${options.base}`,
  189. outdir: `out/release/${options.base}/esm/`,
  190. plugins: [
  191. alias({
  192. 'vscode-nls': path.join(__dirname, 'fillers/vscode-nls.ts')
  193. })
  194. ]
  195. });
  196. }
  197. exports.buildESM = buildESM;
  198. /**
  199. * @param {'dev'|'min'} type
  200. * @param {{
  201. * base: string;
  202. * entryPoint: string;
  203. * amdModuleId: string;
  204. * amdDependencies?: string[];
  205. * }} options
  206. */
  207. function buildOneAMD(type, options) {
  208. /** @type {import('esbuild').BuildOptions} */
  209. const opts = {
  210. entryPoints: [options.entryPoint],
  211. bundle: true,
  212. target: 'esnext',
  213. format: 'iife',
  214. define: {
  215. AMD: 'true'
  216. },
  217. globalName: 'moduleExports',
  218. banner: {
  219. js: `${bundledFileHeader}define("${options.amdModuleId}",[${(options.amdDependencies || [])
  220. .map((dep) => `"${dep}"`)
  221. .join(',')}],()=>{`
  222. },
  223. footer: {
  224. js: 'return moduleExports;\n});'
  225. },
  226. outbase: `src/${options.base}`,
  227. outdir: `out/release/${options.base}/${type}/`,
  228. plugins: [
  229. alias({
  230. 'vscode-nls': path.join(__dirname, '../build/fillers/vscode-nls.ts'),
  231. 'monaco-editor-core': path.join(__dirname, '../build/fillers/monaco-editor-core-amd.ts')
  232. })
  233. ]
  234. };
  235. if (type === 'min') {
  236. opts.minify = true;
  237. }
  238. build(opts);
  239. }
  240. /**
  241. * @param {{
  242. * base: string;
  243. * entryPoint: string;
  244. * amdModuleId: string;
  245. * amdDependencies?: string[];
  246. * }} options
  247. */
  248. function buildAMD(options) {
  249. buildOneAMD('dev', options);
  250. buildOneAMD('min', options);
  251. }
  252. exports.buildAMD = buildAMD;
  253. function getGitVersion() {
  254. const git = path.join(REPO_ROOT, '.git');
  255. const headPath = path.join(git, 'HEAD');
  256. let head;
  257. try {
  258. head = fs.readFileSync(headPath, 'utf8').trim();
  259. } catch (e) {
  260. return void 0;
  261. }
  262. if (/^[0-9a-f]{40}$/i.test(head)) {
  263. return head;
  264. }
  265. const refMatch = /^ref: (.*)$/.exec(head);
  266. if (!refMatch) {
  267. return void 0;
  268. }
  269. const ref = refMatch[1];
  270. const refPath = path.join(git, ref);
  271. try {
  272. return fs.readFileSync(refPath, 'utf8').trim();
  273. } catch (e) {
  274. // noop
  275. }
  276. const packedRefsPath = path.join(git, 'packed-refs');
  277. let refsRaw;
  278. try {
  279. refsRaw = fs.readFileSync(packedRefsPath, 'utf8').trim();
  280. } catch (e) {
  281. return void 0;
  282. }
  283. const refsRegex = /^([0-9a-f]{40})\s+(.+)$/gm;
  284. let refsMatch;
  285. const refs = {};
  286. while ((refsMatch = refsRegex.exec(refsRaw))) {
  287. refs[refsMatch[2]] = refsMatch[1];
  288. }
  289. return refs[ref];
  290. }
  291. const bundledFileHeader = (() => {
  292. const sha1 = getGitVersion();
  293. const semver = require('../package.json').version;
  294. const headerVersion = semver + '(' + sha1 + ')';
  295. const BUNDLED_FILE_HEADER = [
  296. '/*!-----------------------------------------------------------------------------',
  297. ' * Copyright (c) Microsoft Corporation. All rights reserved.',
  298. ' * Version: ' + headerVersion,
  299. ' * Released under the MIT license',
  300. ' * https://github.com/microsoft/monaco-editor/blob/main/LICENSE.txt',
  301. ' *-----------------------------------------------------------------------------*/',
  302. ''
  303. ].join('\n');
  304. return BUNDLED_FILE_HEADER;
  305. })();
  306. exports.bundledFileHeader = bundledFileHeader;
  307. /** @typedef {{ path:string; contents:Buffer;}} IFile */
  308. /**
  309. * @param {string} pattern
  310. * @param {{ base:string; ignore?:string[]; dot?:boolean; }} options
  311. * @returns {IFile[]}
  312. */
  313. function readFiles(pattern, options) {
  314. let files = glob.sync(pattern, { cwd: REPO_ROOT, ignore: options.ignore, dot: options.dot });
  315. // remove dirs
  316. files = files.filter((file) => {
  317. const fullPath = path.join(REPO_ROOT, file);
  318. const stats = fs.statSync(fullPath);
  319. return stats.isFile();
  320. });
  321. const base = options.base;
  322. const baseLength = base === '' ? 0 : base.endsWith('/') ? base.length : base.length + 1;
  323. return files.map((file) => {
  324. const fullPath = path.join(REPO_ROOT, file);
  325. const contents = fs.readFileSync(fullPath);
  326. const relativePath = file.substring(baseLength);
  327. return {
  328. path: relativePath,
  329. contents
  330. };
  331. });
  332. }
  333. exports.readFiles = readFiles;
  334. /**
  335. * @param {IFile[]} files
  336. * @param {string} dest
  337. */
  338. function writeFiles(files, dest) {
  339. for (const file of files) {
  340. const fullPath = path.join(REPO_ROOT, dest, file.path);
  341. ensureDir(path.dirname(fullPath));
  342. fs.writeFileSync(fullPath, file.contents);
  343. }
  344. }
  345. exports.writeFiles = writeFiles;