1// Copyright 2024 The Pigweed Authors 2// 3// Licensed under the Apache License, Version 2.0 (the "License"); you may not 4// use this file except in compliance with the License. You may obtain a copy of 5// the License at 6// 7// https://www.apache.org/licenses/LICENSE-2.0 8// 9// Unless required by applicable law or agreed to in writing, software 10// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12// License for the specific language governing permissions and limitations under 13// the License. 14 15import { existsSync as fsExists } from 'fs'; 16import * as fs from 'fs/promises'; 17import * as path from 'path'; 18import * as process from 'process'; 19import { findPigweedJsonAbove } from '../src/project.js'; 20 21/** Join paths and resolve them in one shot. */ 22const joinResolve = (...paths: string[]) => path.resolve(path.join(...paths)); 23 24/** Get the one argument that can be provided to the script. */ 25const getArg = () => process.argv.at(2); 26 27async function prepostPackage() { 28 const pwRoot = findPigweedJsonAbove(process.cwd()); 29 if (!pwRoot) throw new Error('Could not find Pigweed root!'); 30 31 const extRoot = path.join(pwRoot, 'pw_ide', 'ts', 'pigweed-vscode'); 32 if (!fsExists(extRoot)) throw new Error('Could not find extension root!'); 33 34 // A license file must be bundled with the extension. 35 // Instead of redundantly storing it in this dir, we just temporarily copy 36 // it into this dir when building, then remove it. 37 const licensePath = joinResolve(pwRoot, 'LICENSE'); 38 const tempLicensePath = joinResolve(extRoot, 'LICENSE'); 39 40 // We don't store the icon in the source tree. 41 // We expect to find it in the parent dir of the Pigweed repo dir, and like 42 // the license file, we temporarily copy it for bundling then remove it. 43 const iconPath = joinResolve(path.dirname(pwRoot), 'icon.png'); 44 const tempIconPath = joinResolve(extRoot, 'icon.png'); 45 46 const cleanup = async () => { 47 try { 48 await fs.unlink(tempLicensePath); 49 await fs.unlink(tempIconPath); 50 } catch (err: unknown) { 51 const { code } = err as { code: string }; 52 if (code !== 'ENOENT') throw err; 53 } 54 }; 55 56 const arg = getArg(); 57 58 if (!arg || arg === '--pre') { 59 try { 60 await fs.copyFile(licensePath, tempLicensePath); 61 await fs.copyFile(iconPath, tempIconPath); 62 } catch (err: unknown) { 63 await cleanup(); 64 throw err; 65 } 66 67 return; 68 } 69 70 if (arg === '--post') { 71 await cleanup(); 72 return; 73 } 74 75 console.error(`Unrecognized argument: ${arg}`); 76} 77 78await prepostPackage(); 79