Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
name: Run basic tests

on:
push:
branches: [master]
pull_request:
branches: [master]

jobs:
build:
strategy:
fail-fast: false
matrix:
os: [macos-latest, ubuntu-latest, windows-latest]
runs-on: ${{ matrix.os }}
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Install Node.js
uses: actions/setup-node@v2
with:
node-version: 20
- run: npm install
# - run: npm run vscode:prepublish
- run: npm run lint
9 changes: 7 additions & 2 deletions .vscode/extensions.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
{
// See http://go.microsoft.com/fwlink/?LinkId=827846
// for the documentation about the extensions.json format
"recommendations": ["dbaeumer.vscode-eslint", "connor4312.esbuild-problem-matchers", "ms-vscode.extension-test-runner"]
}
"recommendations": [
"dbaeumer.vscode-eslint",
"connor4312.esbuild-problem-matchers",
"ms-vscode.extension-test-runner",
"cliff-4.file-size-on-toolbar"
]
}
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Change Log

<!-- Check [Keep a Changelog](http://keepachangelog.com/) for recommendations on how to structure this file. -->

## [Unreleased]

- Initial release
23 changes: 22 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,28 @@
"onStartupFinished"
],
"main": "./dist/extension.js",
"contributes": {},
"contributes": {
"configuration": {
"title": "File Size on Toolbar",
"properties": {
"file-size-on-toolbar.applyOnText": {
"type": "boolean",
"default": true,
"description": "Track file size for text files."
},
"file-size-on-toolbar.applyOnNotebooks": {
"type": "boolean",
"default": true,
"description": "Track file size for notebooks."
},
"file-size-on-toolbar.applyOnUntitled": {
"type": "boolean",
"default": true,
"description": "Track file size for unsaved files."
}
}
}
},
"scripts": {
"vscode:prepublish": "npm run package",
"compile": "npm run check-types && npm run lint && node esbuild.js",
Expand Down
154 changes: 114 additions & 40 deletions src/extension.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,15 @@
import * as vscode from "vscode";
import fs from "fs/promises";
import * as packageJson from "../package.json";

function debug(msg: string) {
// console.debug(`[file-size-on-toolbar] ${msg}`);
function debug(msg: any) {
console.debug(`[file-size-on-toolbar] ${msg.toString()}`);
}

async function getFileSizeBytes(path: string): Promise<number> {
try {
const stats = await fs.stat(path);
return stats.size;
} catch (e) {
console.log("Error getting file size:", e);
}
return 0;
async function getFileSizeBytes(uri: vscode.Uri): Promise<number> {
return (await vscode.workspace.fs.readFile(uri)).length;
}

function getSize(s: number): string {
export function bytesToReadableString(s: number): string {
let x = 1024;
if (s < x) {
return (Math.round(100 * s) / 100).toString() + "B";
Expand All @@ -36,71 +30,151 @@ function getSize(s: number): string {
return "TooManyB";
}

function handleOnFocusTitled(sizeView: vscode.StatusBarItem) {
async function getSize(uri: vscode.Uri): Promise<string> {
return await getFileSizeBytes(uri).then(bytesToReadableString, (reason) => {
debug(`Can not parse file size due to: ${reason}`);
return "-1";
});
}

function handleOnFocusText(sizeView: vscode.StatusBarItem) {
return async () => {
debug(`handleOnFocus triggered`);
let editor = vscode.window.activeTextEditor;
if (editor === undefined) {
sizeView.text = "";
return;
}
let notebook = vscode.window.activeNotebookEditor?.notebook;
if (notebook !== undefined) {
return;
}
if (
!vscode.workspace.getConfiguration(ExtSet.Name).get(ExtSet.Text) ||
editor === undefined
) {
sizeView.text = "";
return;
}
if (editor.document.isUntitled) {
sizeView.text = getSize(editor?.document.getText().length);
return;
}
debug(`Editor defined`);
let sizeStr = getSize(await getFileSizeBytes(editor.document.fileName));
debug(`Size of ${editor.document.fileName}: ${sizeStr}`);
let sizeStr = await getSize(editor.document.uri);
debug(
`[Text] Size of ${editor.document.fileName
.split("\\")
.at(-1)}: ${sizeStr}`
);
sizeView.text = sizeStr;
};
}

function handleOnFocusNotebook(sizeView: vscode.StatusBarItem) {
return async () => {
let editor = vscode.window.activeNotebookEditor;
if (editor === undefined) {
return;
}
let v = vscode.workspace.getConfiguration(ExtSet.Name);
if (
vscode.workspace
.getConfiguration(ExtSet.Name)
.get(ExtSet.Notebook) === false ||
editor.notebook.isUntitled
) {
sizeView.text = "";
return;
}

let sizeStr = await getSize(editor.notebook.uri);
debug(
`Size of ${editor.notebook.uri
.toString()
.split("/")
.at(-1)}: ${sizeStr}`
);
sizeView.text = sizeStr;
};
}

function handleOnFocusUntitled(sizeView: vscode.StatusBarItem) {
return async () => {
debug(`handleOnFocus triggered`);
let editor = vscode.window.activeTextEditor;
if (editor === undefined) {
sizeView.text = "";
return;
}
if (!editor.document.isUntitled) {
let notebook = vscode.window.activeNotebookEditor?.notebook.uri;
if (
notebook !== undefined ||
(editor !== undefined && !editor.document.isUntitled)
) {
return;
}
debug(`Editor defined`);
let sizeStr = getSize(editor.document.getText().length);
debug(`Size of ${editor.document.fileName}: ${sizeStr}`);
if (
vscode.workspace
.getConfiguration(ExtSet.Name)
.get(ExtSet.Untitled) === false ||
editor === undefined
) {
sizeView.text = "";
return;
}

let sizeStr = bytesToReadableString(editor.document.getText().length);
debug(
`[Untitled] Size of ${editor.document.fileName
.split("\\")
.at(-1)}: ${sizeStr}`
);
sizeView.text = sizeStr;
};
}

const subscribedEvents = [
vscode.workspace.onDidSaveTextDocument,
vscode.workspace.onDidSaveNotebookDocument,
vscode.window.onDidChangeActiveTextEditor,
vscode.window.onDidChangeActiveNotebookEditor,
];
enum ExtSet {
Name = "file-size-on-toolbar",
Text = "applyOnText",
Notebook = "applyOnNotebooks",
Untitled = "applyOnUntitled",
None = "",
}

export async function activate(context: vscode.ExtensionContext) {
debug("Active");
debug(
`Currently subscribed to ${
subscribedEvents.length
} events\n- ${subscribedEvents.map((func) => func.name).join("\n- ")}`
);
debug(`${packageJson.name}v${packageJson.version} is Active`);

let sizeView = vscode.window.createStatusBarItem(2, 4);
sizeView.tooltip = "File Size Information";
sizeView.show();
await handleOnFocusTitled(sizeView)();

context.subscriptions.push(
...subscribedEvents.map((func) => func(handleOnFocusTitled(sizeView)))
);
// await handleOnFocusText(sizeView)();

context.subscriptions.push(
vscode.workspace.onDidSaveTextDocument(handleOnFocusText(sizeView)),
vscode.window.onDidChangeActiveTextEditor(handleOnFocusText(sizeView)),

vscode.workspace.onDidSaveNotebookDocument(
handleOnFocusNotebook(sizeView)
),
vscode.window.onDidChangeActiveNotebookEditor(
handleOnFocusNotebook(sizeView)
),

vscode.workspace.onDidChangeTextDocument(
handleOnFocusUntitled(sizeView)
)
),
vscode.window.onDidChangeActiveTextEditor(
handleOnFocusUntitled(sizeView)
),
vscode.workspace.onDidChangeConfiguration((e) => {
if (e.affectsConfiguration(ExtSet.Name + "." + ExtSet.Notebook)) {
debug("Notebook conf changed");
}
if (e.affectsConfiguration(ExtSet.Name + "." + ExtSet.Text)) {
debug("Text conf changed");
}
if (e.affectsConfiguration(ExtSet.Name + "." + ExtSet.Untitled)) {
debug("Untitled conf changed");
}
})
);
}

Expand Down
13 changes: 13 additions & 0 deletions src/test/extension.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import * as assert from "assert";

import * as vscode from "vscode";
import * as myExtension from "../extension";

suite("Extension Test Suite", () => {
vscode.window.showInformationMessage("Start all tests.");

test("Test bytesToReadableString", () => {
assert.strictEqual("1KB", myExtension.bytesToReadableString(1024));
assert.strictEqual("1023B", myExtension.bytesToReadableString(1023));
});
});
5 changes: 3 additions & 2 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,11 @@
],
"sourceMap": true,
"rootDir": "src",
"strict": true /* enable all strict type-checking options */
"strict": true, /* enable all strict type-checking options */
/* Additional Checks */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
"resolveJsonModule": true, // for importing PackageJson
}
}
}
Loading