Skip to content

Commit

Permalink
Clean-up
Browse files Browse the repository at this point in the history
Signed-off-by: paulober <[email protected]>
  • Loading branch information
paulober committed Apr 2, 2024
1 parent 9c2362b commit 2c17294
Show file tree
Hide file tree
Showing 11 changed files with 443 additions and 305 deletions.
137 changes: 137 additions & 0 deletions .yarn/plugins/list-plugin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
const fs = require("fs");

// Setup: Place this file in `.yarn/plugins/list-plugin.js` and the following
// to `.yarnrc.yml`:
//
// ```
// plugins:
// - path: .yarn/plugins/plugin-list.js
// ```
module.exports = {
name: "plugin-list",
factory: (require) => {
const { BaseCommand } = require("@yarnpkg/cli");
const { Command, Option } = require("clipanion");
const { parseSyml } = require("@yarnpkg/parsers");

class ListCommand extends BaseCommand {
static paths = [["list"]];

static usage = Command.Usage({
description: "Lists installed packages.",
});

prod = Option.Boolean("--prod", false);
json = Option.Boolean("--json", false);

async execute() {
if (!this.prod || !this.json) {
throw new Error(
"This command can only be used with the --prod and --json " +
"args to match the behavior required by VSCE. See: " +
"https://github.com/microsoft/vscode-vsce/blob/main/src/npm.ts",
);
}

const packageJsonContents = fs.readFileSync("package.json", "utf-8");
const { dependencies = {} } = JSON.parse(packageJsonContents);

const lockContents = fs.readFileSync("yarn.lock", "utf-8");
const resolved = parseSyml(lockContents);

const trees = [];

function addDependency(packageName, versionRange) {
const packageInfo = lookup(
resolved,
getLockFileKey(packageName, versionRange),
);
if (!packageInfo) {
throw new Error(
`Cannot resolve "${packageName}" with version range "${versionRange}"`,
);
}

const { version, dependencies } = packageInfo;
const name = `${packageName}@${version}`;
if (trees.find((tree) => tree.name === name)) {
return; // Dependency already added as part of another tree.
}

if (dependencies) {
const children = Object.entries(dependencies).map(
([name, range]) => ({ name: `${name}@${range}` }),
);
trees.push({ name, children });

addDependencies(dependencies);
} else {
trees.push({ name, children: [] });
}
}

function addDependencies(dependencies) {
for (const [packageName, versionRange] of Object.entries(
dependencies,
)) {
addDependency(packageName, versionRange);
}
}

addDependencies(dependencies);

const output = {
type: "tree",
data: { type: "list", trees },
};

this.context.stdout.write(JSON.stringify(output));
}
}

return {
commands: [ListCommand],
};
},
};

function getLockFileKey(packageName, versionSpecifier) {
// If the version field contains a URL, don't attempt to use the NPM registry
return versionSpecifier.includes(":")
? `${packageName}@${versionSpecifier}`
: `${packageName}@npm:${versionSpecifier}`;
}

/**
* @param resolved All the resolved dependencies as found in the lock file.
* @param dependencyKey Key of the dependency to look up. Can be created using
* `lockFileKey()`.
*/
function lookup(resolved, dependencyKey) {
let packageInfo;
if (dependencyKey.includes("file:")) {
const keys = Object.keys(resolved);

for (let i = 0; i < keys.length; i++) {
const key = keys[i];

if (key.includes(dependencyKey)) {
packageInfo = resolved[key];
break;
}
}
} else {
packageInfo = resolved[dependencyKey];
}
if (packageInfo) {
return packageInfo;
}

// Fall back to slower iteration-based lookup for combined keys.
for (const [key, packageInfo] of Object.entries(resolved)) {
if (key.split(",").some((key) => key.trim() === dependencyKey)) {
return packageInfo;
}
}
}

7 changes: 7 additions & 0 deletions .yarnrc.yml
Original file line number Diff line number Diff line change
@@ -1 +1,8 @@
compressionLevel: mixed

enableGlobalCache: false

plugins:
- path: .yarn/plugins/list-plugin.js

yarnPath: .yarn/releases/yarn-4.1.1.cjs
7 changes: 4 additions & 3 deletions src/activitybar/flipperAppDevProvider.mts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import {
EventEmitter,
ProviderResult,
type ProviderResult,
ThemeIcon,
TreeDataProvider,
type TreeDataProvider,
TreeItem,
TreeItemCollapsibleState,
Event,
type Event,
} from "vscode";
import { UfbtSDKBranch, ufbtGetSelectedChannel } from "../helper/ufbt.mjs";
import { EXTENSION_NAME } from "../constants.mjs";
Expand Down Expand Up @@ -48,6 +48,7 @@ export class FlipperAppDevProvider implements TreeDataProvider<SDKChannel> {
title: "Switch SDK",
arguments: [element.branch],
};

return element;
}

Expand Down
4 changes: 2 additions & 2 deletions src/commands/buildFap.mts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export default class BuildFapCommand extends Command {
super(BuildFapCommand.id);
}

async execute(): Promise<void> {
await ufbtBuild();
execute(): void {
ufbtBuild();
}
}
4 changes: 2 additions & 2 deletions src/commands/launchFap.mts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export default class LaunchFapCommand extends Command {
super(LaunchFapCommand.id);
}

async execute(): Promise<void> {
await ufbtLaunch();
execute(): void {
ufbtLaunch();
}
}
9 changes: 2 additions & 7 deletions src/commands/openSerial.mts
Original file line number Diff line number Diff line change
@@ -1,9 +1,4 @@
import { Command } from "./command.mjs";
import { type Terminal, window, workspace } from "vscode";
import { join as joinPosix } from "path/posix";
import { SDKS_FOLDER_NAME } from "../constants.mjs";
import { homedir } from "os";
import { dirname } from "path";
import { ufbtCli } from "../helper/ufbt.mjs";

export default class OpenSerialCommand extends Command {
Expand All @@ -13,7 +8,7 @@ export default class OpenSerialCommand extends Command {
super(OpenSerialCommand.id);
}

async execute(): Promise<void> {
await ufbtCli();
execute(): void {
ufbtCli();
}
}
15 changes: 9 additions & 6 deletions src/commands/switchSDK.mts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { window } from "vscode";
import { CommandWithArgs } from "./command.mjs";
import { UfbtSDKBranch, ufbtSwitchSDK } from "../helper/ufbt.mjs";
import { FlipperAppDevProvider } from "../activitybar/flipperAppDevProvider.mjs";
// eslint-disable-next-line max-len
import type { FlipperAppDevProvider } from "../activitybar/flipperAppDevProvider.mjs";

export default class SwitchSDKCommand extends CommandWithArgs {
public static readonly id = "switchSDK";
Expand All @@ -15,7 +16,9 @@ export default class SwitchSDKCommand extends CommandWithArgs {
const result = await window.showQuickPick(
["$(check) Yes", "$(chrome-close) No"],
{
placeHolder: `Do you realy want to switch your selected SDK to the ${branch} branch?`,
placeHolder:
"Do you realy want to switch your selected " +
`SDK to the ${branch} branch?`,
canPickMany: false,
ignoreFocusOut: false,
title: "Switch SDK",
Expand All @@ -26,7 +29,7 @@ export default class SwitchSDKCommand extends CommandWithArgs {
return;
}

await ufbtSwitchSDK(branch);
ufbtSwitchSDK(branch);
// wait 2 seconds
await new Promise(resolve => setTimeout(resolve, 2000));
this._flipperAppDevProvider.refresh();
Expand All @@ -50,13 +53,13 @@ export default class SwitchSDKCommand extends CommandWithArgs {

switch (sdkBranch) {
case "Release":
await ufbtSwitchSDK(UfbtSDKBranch.release);
ufbtSwitchSDK(UfbtSDKBranch.release);
break;
case "Release-candidate":
await ufbtSwitchSDK(UfbtSDKBranch.rc);
ufbtSwitchSDK(UfbtSDKBranch.rc);
break;
case "Dev":
await ufbtSwitchSDK(UfbtSDKBranch.dev);
ufbtSwitchSDK(UfbtSDKBranch.dev);
break;
}

Expand Down
5 changes: 0 additions & 5 deletions src/constants.mts
Original file line number Diff line number Diff line change
@@ -1,6 +1 @@
export const EXTENSION_NAME = "flipper-app-dev";
export const SDKS_FOLDER_NAME = ".flipper-sdk";

export const OFW_GITHUB_OWNER = "flipperdevices";
export const OFW_GITHUB_REPO = "flipperzero-firmware";
export const OFW_GITHUB_BRANCH = "dev";
41 changes: 30 additions & 11 deletions src/helper/ufbt.mts
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
import { exec } from "child_process";
import { existsSync, readFileSync } from "fs";
import { homedir } from "os";
import { dirname, join } from "path";
import { join } from "path";
import { promisify } from "util";
import { Terminal, ThemeIcon, Uri, window, workspace } from "vscode";
import { type Terminal, ThemeIcon, type Uri, window, workspace } from "vscode";
import { getShellRoot } from "./fsHelper.mjs";
import { EXTENSION_NAME } from "../constants.mjs";
import { writeFile } from "fs/promises";

const execAsync = promisify(exec);

export async function installUfbt(): Promise<boolean> {
const { stdout, stderr } = await execAsync(
const { stderr } = await execAsync(
process.platform === "win32"
? "py -m pip install -U ufbt"
: "python3 -m pip install -U ufbt"
Expand All @@ -19,7 +21,8 @@ export async function installUfbt(): Promise<boolean> {
console.error(stderr);

void window.showErrorMessage(
"An error occurred while installing ufbt. Please check the output for more information: " +
"An error occurred while installing ufbt. " +
"Please check the output for more information: " +
stderr
);

Expand All @@ -38,13 +41,27 @@ export async function ufbtNewApp(appId: string, folder: Uri): Promise<void> {
console.error(stderr);

void window.showErrorMessage(
"An error occurred while creating a new app. Please check the output for more information: " +
"An error occurred while creating a new app. " +
"Please check the output for more information: " +
stderr
);

return;
}

// add paulober.flipper-app-dev to the recommended extensions in folder/.vscode/extensions.json
const extensionsPath = join(folder.fsPath, ".vscode", "extensions.json");
const extensions = existsSync(extensionsPath)
? (JSON.parse(readFileSync(extensionsPath, "utf8")) as {
recommendations: string[];
})
: { recommendations: [] };
extensions.recommendations = [
...(extensions.recommendations ?? []),
`paulober.${EXTENSION_NAME}`,
];
await writeFile(extensionsPath, JSON.stringify(extensions, null, 4));

void window.showInformationMessage("Created new app successfully.");

workspace.updateWorkspaceFolders(
Expand All @@ -60,7 +77,7 @@ export async function ufbtNewApp(appId: string, folder: Uri): Promise<void> {
let ufbtBuildTerminal: Terminal | undefined;
let ufbtConsoleTerminal: Terminal | undefined;

export async function ufbtLaunch(): Promise<void> {
export function ufbtLaunch(): void {
if (!workspace.workspaceFolders || workspace.workspaceFolders.length === 0) {
void window.showErrorMessage("No open flipper application folder found.");

Expand Down Expand Up @@ -93,7 +110,7 @@ export async function ufbtLaunch(): Promise<void> {
ufbtBuildTerminal.show();
}

export async function ufbtCli(): Promise<void> {
export function ufbtCli(): void {
if (ufbtConsoleTerminal) {
ufbtConsoleTerminal.dispose();
}
Expand All @@ -111,7 +128,7 @@ export async function ufbtCli(): Promise<void> {
ufbtConsoleTerminal.show();
}

export async function ufbtBuild(): Promise<void> {
export function ufbtBuild(): void {
if (!workspace.workspaceFolders || workspace.workspaceFolders.length === 0) {
void window.showErrorMessage("No open flipper application folder found.");

Expand Down Expand Up @@ -144,7 +161,7 @@ export enum UfbtSDKBranch {
dev = "dev",
}

export async function ufbtSwitchSDK(branch: UfbtSDKBranch): Promise<void> {
export function ufbtSwitchSDK(branch: UfbtSDKBranch): void {
if (!workspace.workspaceFolders || workspace.workspaceFolders.length === 0) {
void window.showErrorMessage("No open flipper application folder found.");

Expand Down Expand Up @@ -177,7 +194,7 @@ export async function ufbtSwitchSDK(branch: UfbtSDKBranch): Promise<void> {
}

export async function ufbtClean(): Promise<void> {
const { stdout, stderr } = await execAsync("ufbt clean", {
const { stderr } = await execAsync("ufbt clean", {
cwd: homedir(),
});

Expand All @@ -203,21 +220,23 @@ export function ufbtGetSelectedChannel(): string | null {
// Read the file content
const fileContent = readFileSync(filePath, "utf8");
// Parse JSON content
const jsonData = JSON.parse(fileContent);
const jsonData = JSON.parse(fileContent) as { channel: string } | null;
// Check if 'channel' property exists in the JSON data
if (jsonData && jsonData.channel) {
return jsonData.channel;
} else {
console.error(
"Channel property not found in the ufbt state JSON data."
);

return null;
}
} else {
return null;
}
} catch (err) {
console.error("Error reading ufbt state:", err);

return null;
}
}
Loading

0 comments on commit 2c17294

Please sign in to comment.