Skip to content

Commit

Permalink
fix(scriptlet): use invoke-pty. During pnpm install, attempt to load …
Browse files Browse the repository at this point in the history
…all shell env vars
  • Loading branch information
johnlindquist committed Dec 17, 2024
1 parent f078789 commit 1316c5f
Show file tree
Hide file tree
Showing 13 changed files with 165 additions and 179 deletions.
15 changes: 3 additions & 12 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,7 @@
"bugs": {
"url": "https://github.com/script-kit/kitapp/issues"
},
"keywords": [
"electron",
"react",
"typescript",
"ts"
],
"keywords": ["electron", "react", "typescript", "ts"],
"homepage": "https://github.com/script-kit/kitapp#readme",
"devDependencies": {
"@biomejs/biome": "^1.9.4",
Expand Down Expand Up @@ -201,12 +196,8 @@
},
"browserslist": [],
"renovate": {
"extends": [
"bliss"
],
"baseBranches": [
"next"
]
"extends": ["bliss"],
"baseBranches": ["next"]
},
"jest": {
"preset": "ts-jest",
Expand Down
34 changes: 34 additions & 0 deletions src/main/env-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,37 @@ export const loadKenvEnvironment = (): kenvEnv => {

return envData;
};

import { shellEnv } from 'shell-env';

interface ShellEnvType {
[key: string]: string | undefined;
}

export async function getAllShellEnvs(): Promise<ShellEnvType> {
const allEnvs: ShellEnvType = {};
const shells = ['/bin/bash', '/bin/zsh', '/usr/bin/fish']; // Unix shells.
// Add Windows if we're on that OS and looking for Git Bash.
if (process.platform === 'win32') {
const gitBashPath = path.join(process.env.ProgramFiles || '', 'Git', 'bin', 'bash.exe');
shells.push(gitBashPath);
}

for (const shell of shells) {
try {
const env = await shellEnv(shell);
Object.assign(allEnvs, env);
log.info(`Successfully loaded environment variables from ${shell}`);
} catch (error) {
if (error instanceof Error) {
log.silly(`Error loading environment variables from ${shell}: ${error.message}`);
} else {
log.silly(`An unknown error occurred while loading environment variables from ${shell}`);
}
}
}

// Merge Node process.env
Object.assign(allEnvs, process.env);
return allEnvs;
}
4 changes: 2 additions & 2 deletions src/main/env.utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { snapshot } from 'valtio';
import { kitState, kitStore } from './state';
import { getVersion } from './version';

export const createEnv = () => {
export const createEnv = (): Readonly<Partial<Record<string, string>>> => {
const PATH = KIT_FIRST_PATH + path.delimiter + process?.env?.PATH;

return {
Expand All @@ -20,7 +20,7 @@ export const createEnv = () => {
FORCE_COLOR: '1',
PATH,
KIT_APP_PATH: app.getAppPath(),
KIT_ACCESSIBILITY: kitState.isMac && kitStore.get('accessibilityAuthorized'),
KIT_ACCESSIBILITY: kitState.isMac && kitStore.get('accessibilityAuthorized') ? 'true' : 'false',
...snapshot(kitState.kenvEnv),
};
};
61 changes: 18 additions & 43 deletions src/main/install.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@ import { INSTALL_ERROR, show } from './show';
import { getThemes, kitCache, kitState, preloadChoicesMap, workers } from './state';
import { ensureDir, writeFile, readJson, writeJson, pathExists, readdir } from './cjs-exports';


import electronLog from 'electron-log';
import { createLogger } from '../shared/log-utils';
import { createForkOptions } from './fork.options';
Expand All @@ -53,7 +52,7 @@ import { getPnpmPath } from './setup/pnpm';
import { shortcutMap } from './shortcuts';
import { showInfo } from './info';
import { compareCollections, logDifferences } from './compare';

import { getAllShellEnvs } from './env-utils';
const log = createLogger('install.ts');

let isOhNo = false;
Expand Down Expand Up @@ -541,12 +540,11 @@ export const cleanKit = async () => {
log.info(`Continuing with new Kit SDK at ${kitPath()}`);
} catch (error) {
log.error(`Error cleaning the Kit SDK at: ${kitPath()}`, error);
log.error(`Please close any open code editors which might be referencing ~/.kit or ~/.kenv and try again.`)
log.error(`Please close any open code editors which might be referencing ~/.kit or ~/.kenv and try again.`);
throw new Error(`Error cleaning ${kitPath()}`);
}
};


export const installKitDeps = async () => {
const pnpmPath = await getPnpmPath();
await requiredSpawnSetup(pnpmPath, ['i', '--prod'], {
Expand Down Expand Up @@ -577,17 +575,17 @@ export const extractKitTar = async (file: string) => {
};

export const downloadKit = async () => {
let appVersion = ''
let appVersion = '';

if(process.env.NODE_ENV === 'development') {
if (process.env.NODE_ENV === 'development') {
appVersion = await getLatestAppTag();
log.info(`Using latest app tag: ${appVersion}`);
}else{
} else {
appVersion = getVersion();
log.info(`Using app version: ${appVersion}`);
}
if(appVersion?.startsWith('v')){
appVersion = appVersion.slice(1)
if (appVersion?.startsWith('v')) {
appVersion = appVersion.slice(1);
}

const extension = 'tar.gz';
Expand All @@ -611,7 +609,6 @@ export const downloadKit = async () => {

log.info(`Fallback SDK URL: ${fallbackUrl}`);


let url: string;
try {
let sdkVersion = '' as 'latest' | 'next' | string;
Expand Down Expand Up @@ -1101,22 +1098,15 @@ interface CacheMainScripts {
}

// Helper function to resolve all pending promises at once
function resolveAllPending(
resolvers: Array<{ resolve: (value: boolean) => void }>,
uuid: string
) {
function resolveAllPending(resolvers: Array<{ resolve: (value: boolean) => void }>, uuid: string) {
for (const { resolve } of resolvers) {
log.info(`Resolving ${uuid}`);
resolve(true);
}
}

// Helper function to reject all pending promises at once
function rejectAllPending(
resolvers: Array<{ reject: (reason?: any) => void }>,
uuid: string,
error: any
) {
function rejectAllPending(resolvers: Array<{ reject: (reason?: any) => void }>, uuid: string, error: any) {
for (const { reject } of resolvers) {
log.info(`Rejecting ${uuid}`);
reject(error);
Expand All @@ -1130,7 +1120,7 @@ function ensureWorker(
handleReject: (error: any) => void,
messageHandler: (message: any) => void,
errorHandler: (error: any) => void,
messageErrorHandler: (error: any) => void
messageErrorHandler: (error: any) => void,
) {
if (!workers.cacheScripts) {
log.info(`Creating worker: ${CACHED_GROUPED_SCRIPTS_WORKER}...`);
Expand All @@ -1150,11 +1140,7 @@ function ensureWorker(
}

// Message handler: handles different message channels from worker
function createMessageHandler(
uuid: string,
handleResolve: () => void,
handleReject: (error: any) => void
) {
function createMessageHandler(uuid: string, handleResolve: () => void, handleReject: (error: any) => void) {
return (message: any) => {
try {
scriptLog.log('Worker message:', message.channel);
Expand All @@ -1169,11 +1155,7 @@ function createMessageHandler(
// If there's an error in the response
if (message?.error) {
scriptLog.error('Error caching main scripts', message.error);
showInfo(
message.error?.message || 'Check logs...',
'Error...',
message.error?.stack || 'Check logs'
);
showInfo(message.error?.message || 'Check logs...', 'Error...', message.error?.stack || 'Check logs');
handleReject(message.error);
} else {
// Successfully cached scripts
Expand All @@ -1189,11 +1171,7 @@ function createMessageHandler(
}

// Generic error handler for worker-level errors
function createErrorHandler(
uuid: string,
stamp: Stamp | null,
handleReject: (error: any) => void
) {
function createErrorHandler(uuid: string, stamp: Stamp | null, handleReject: (error: any) => void) {
return (error: any) => {
try {
log.info('Received error for stamp', stamp);
Expand All @@ -1207,11 +1185,7 @@ function createErrorHandler(
}

// Generic messageerror handler for worker-level messaging errors
function createMessageErrorHandler(
uuid: string,
stamp: Stamp | null,
handleReject: (error: any) => void
) {
function createMessageErrorHandler(uuid: string, stamp: Stamp | null, handleReject: (error: any) => void) {
return (error: any) => {
try {
log.info('Received message error for stamp', stamp);
Expand All @@ -1235,7 +1209,7 @@ export const cacheMainScripts: CacheMainScripts = async (
} = {
channel: Channel.CACHE_MAIN_SCRIPTS,
value: null,
}
},
): Promise<boolean> => {
log.info(`🎁 cacheMainScripts: ${reason}`);
return new Promise<boolean>((resolve, reject) => {
Expand Down Expand Up @@ -1307,7 +1281,7 @@ export const cacheMainScripts: CacheMainScripts = async (
250,
{
leading: true,
}
},
);
}

Expand All @@ -1322,7 +1296,6 @@ export const cacheMainScripts: CacheMainScripts = async (
});
};


// pnpm might trigger a node download, so we need to wait until the final line prints out the version
export const spawnP = async (
command: string,
Expand All @@ -1332,12 +1305,14 @@ export const spawnP = async (
const KIT = kitPath();
const KENV = kenvPath();

const envResult = await getAllShellEnvs();
const options: SpawnOptions = {
cwd: kitPath(), // Set the current working directory based on the provided parameter
env: {
KIT,
KENV,
PATH: KIT_FIRST_PATH + path.delimiter + process?.env?.PATH,
...envResult,
},
stdio: 'pipe',
shell: true,
Expand Down
Loading

0 comments on commit 1316c5f

Please sign in to comment.