New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

vscode-zap

Package Overview
Dependencies
Maintainers
1
Versions
107
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

vscode-zap - npm Package Compare versions

Comparing version 0.0.47 to 0.0.48

3

out/src/controller.d.ts

@@ -16,2 +16,5 @@ import * as vscode from "vscode";

private attach();
private autoCheckoutRemote(refInfo?);
autoStartWorkspace(): Promise<void>;
private reset(mergeStrategy);
dispose(): void;

@@ -18,0 +21,0 @@ queryRefInfo(refID: RefIdentifier): Thenable<RefInfoResult>;

@@ -15,2 +15,3 @@ "use strict";

const workspace_1 = require("./workspace");
const status_1 = require("./status");
class Controller {

@@ -76,7 +77,60 @@ constructor(serverOptions, clientOptions, environment) {

ref: this.environment.zapRef,
}, this.workspace, mergeStrategy)
.then(() => null, (err) => {
}, this.workspace, mergeStrategy).then(() => null, (err) => {
console.error(`Error watching repo: ${err} ${err.stack}`);
});
}
autoCheckoutRemote(refInfo) {
return __awaiter(this, void 0, void 0, function* () {
if (!refInfo) {
try {
refInfo = yield this.queryRefInfo({ repo: vscode.workspace.rootPath, ref: "HEAD" });
let web = { title: "Open" };
vscode.window.showInformationMessage("Open workspace on Sourcegraph", web).then(cb => {
if (cb === web) {
return vscode.commands.executeCommand("zap.web.openWorkspaceInBrowser");
}
});
vscode.window.setStatusBarMessage("Zap workspace configured", 5000);
}
catch (err) {
status_1.outputChannel.show();
status_1.outputChannel.appendLine(`Error fetching workspace remote HEAD data - ${err}`);
}
}
});
}
// This is used to automatically start the workspace when booting the extension.
autoStartWorkspace() {
return __awaiter(this, void 0, void 0, function* () {
if (this.environment.zapRef !== "HEAD") {
return this.start();
}
try {
yield vscode.commands.executeCommand("zap.localServer.start");
const didConfigure = yield vscode.commands.executeCommand("zap.workspace.configureOrigin");
if (didConfigure) {
yield vscode.commands.executeCommand("zap.branch.configureUpstream");
}
return this.start().then(() => __awaiter(this, void 0, void 0, function* () {
yield this.autoCheckoutRemote();
return Promise.resolve();
}), (err) => __awaiter(this, void 0, void 0, function* () {
status_1.outputChannel.appendLine(`Could not connect to Zap Local Server. Attempting to Reconnect.`);
status_1.outputChannel.show();
return Promise.reject(err);
}));
}
catch (err) {
status_1.outputChannel.appendLine(`Error starting workspace: ${err}`);
}
});
}
reset(mergeStrategy) {
return this.handler.resetWorkspaceRefState({
repo: this.environment.repo,
ref: this.environment.zapRef,
}, this.workspace, mergeStrategy).then(() => null, (err) => {
console.error(`Error watching repo: ${err} ${err.stack}`);
});
}
dispose() {

@@ -116,3 +170,3 @@ if (this.client.needsStop()) {

for (const ref of refs) {
if (ref.repo === this.environment.repo) {
if (ref.repo === this.environment.repo && !ref.ref.startsWith("refs/remotes/")) {
let onSelect = undefined;

@@ -124,10 +178,6 @@ let label = ref.ref;

}
if (ref.ref.startsWith("refs/remotes/")) {
label = "$(circle-slash) " + label;
onSelect = () => vscode.window.showErrorMessage("Switching to a remote-tracking Zap branch is not allowed.");
}
items.push({
label,
description: ref.target ? `$(arrow-right) ${ref.target}` : `${ref.rev} revisions $(git - branch) ${ref.gitBranch}@${ref.gitBase.slice(0, 6)} `,
detail: ref.watchers ? `Watchers: ${ref.watchers.join(" ")} ` : undefined,
description: ref.watchers ? `Watchers: ${ref.watchers.join(" ")} ` : "No current watchers",
detail: "Switch to this branch and start editing",
onSelect: onSelect ? onSelect : () => this.environment.zapRef = ref.ref,

@@ -137,2 +187,18 @@ });

}
if (this.environment.zapRef === "HEAD") {
items.push({
label: "$(x) Clobber Local Changes",
description: "Resets the zap state to match the remote state",
onSelect: () => {
this.reset(handler_1.MergeStrategy.RemoteClobbersLocal);
},
});
items.push({
label: "$(x) Clobber Remote Changes",
description: "Overwrites the zap remote branch with your current state",
onSelect: () => {
this.reset(handler_1.MergeStrategy.LocalClobbersRemote);
},
});
}
items.push({

@@ -139,0 +205,0 @@ label: "$(x) Turn Zap Off",

2

out/src/e2e.js

@@ -305,3 +305,3 @@ "use strict";

return "warning";
case "":
case "white":
return "ok";

@@ -308,0 +308,0 @@ default:

@@ -40,3 +40,3 @@ "use strict";

if (ref !== "HEAD") {
console.warn(`Attempting to set zap ref to ${ref} instead of HEAD which is currently unsupported in the extension`);
vscode.window.showWarningMessage(`Attempting to set Zap ref to ${ref} instead of HEAD, which is currently unsupported in the extension`);
return;

@@ -43,0 +43,0 @@ }

@@ -6,4 +6,3 @@ import * as vscode from "vscode";

export declare function isEnabled(): boolean;
export declare function isWebEnv(): boolean;
export declare function startController(controller: Controller): Thenable<void>;
export declare function stopController(controller: Controller): Thenable<void>;

@@ -16,3 +16,2 @@ // This is the extension's shared entrypoint. All platforms call this

const status_1 = require("./status");
const protocol_1 = require("libzap/lib/remote/protocol");
function activate(env, ctx) {

@@ -37,4 +36,10 @@ if (!vscode.workspace.rootPath) {

})));
let shouldAutostart = !process.env.ZAP_E2E_NAME;
const updateEnabled = (enabled) => {
if (enabled) {
if (shouldAutostart) {
controller.autoStartWorkspace();
shouldAutostart = false;
return;
}
startController(controller);

@@ -54,16 +59,2 @@ }

updateEnabled(isEnabled());
ctx.subscriptions.push(vscode.commands.registerCommand("zap.enableAndAddWorkspace", () => __awaiter(this, void 0, void 0, function* () {
try {
yield vscode.workspace.getConfiguration("zap").update("enable", true, true);
yield startController(controller);
}
catch (err) {
if (err.code === protocol_1.ErrorCode.ErrorCodeWorkspaceExists) {
return;
}
status_1.outputChannel.appendLine(`Enabling Zap in this workspace failed: ${err}`);
status_1.outputChannel.show();
vscode.window.showErrorMessage("Enabling Zap in this workspace failed.");
}
})));
return controller;

@@ -79,12 +70,7 @@ }

exports.isEnabled = isEnabled;
function isWebEnv() {
return process.env.NODE_ENV && !vscode.workspace.getConfiguration("zap").get("_test") && !process.env.CI;
}
exports.isWebEnv = isWebEnv;
function startController(controller) {
return controller.start().then(() => { }, err => {
console.log(`Zap failed to start: ${err}`);
status_1.outputChannel.appendLine(`Zap failed to start: ${err}`);
status_1.outputChannel.show();
vscode.window.showErrorMessage(`Zap failed to start.`);
return controller.start().then(() => {
/* noop */
}, (err) => {
status_1.outputChannel.appendLine(`Error starting the controller: ${err}`);
});

@@ -96,3 +82,3 @@ }

return controller.stop().then(() => { }, err => {
console.error(`Zap failed to stop: ${err}`);
status_1.outputChannel.appendLine(`Zap failed to stop: ${err}`);
});

@@ -99,0 +85,0 @@ }

@@ -21,3 +21,7 @@ // This is the extension's entrypoint used by vscode. Things in here

ctx.subscriptions.push(vscode.commands.registerCommand("zap.install", () => zapLocalServer.install()));
ctx.subscriptions.push(vscode.commands.registerCommand("zap.localServer.start", () => zapLocalServer.startLocalServer()));
ctx.subscriptions.push(vscode.commands.registerCommand("zap.workspace.configureOrigin", () => zapLocalServer.autoConfigureRemotes()));
ctx.subscriptions.push(vscode.commands.registerCommand("zap.branch.configureUpstream", () => zapLocalServer.autoCheckoutRemoteBranch()));
web_1.activate(ctx);
vscode.commands.executeCommand("zap.localServer.start");
return extension_common_1.activate(environment_vscode_1.default, ctx);

@@ -24,0 +28,0 @@ }

export declare function promptToInstall(): Promise<boolean>;
export declare function install(): Promise<void>;
export declare function autoConfigureRemotes(): Promise<boolean>;
export declare function autoCheckoutRemoteBranch(): Promise<void>;
export declare function startLocalServer(): Promise<void>;
export declare function zapExecutable(): string;

@@ -10,5 +10,16 @@ "use strict";

};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
const sp = require("child_process");
const vscode = require("vscode");
const status_1 = require("./status");
const net = require("net");
const fs = require("fs");
const path = require("path");
function promptToInstall() {

@@ -51,2 +62,93 @@ return new Promise((resolve, reject) => {

exports.install = install;
function autoConfigureRemotes() {
return __awaiter(this, void 0, void 0, function* () {
return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
const ghRemote = sp.spawn(`git ls-remote --get-url | sed 's/.*://;s/.git$//'`, [], {
shell: true,
cwd: vscode.workspace.rootPath,
});
const webURL = vscode.workspace.getConfiguration("zap").get("web.url");
ghRemote.stdout.on("data", (ghRemoteData) => {
const zapRemote = ghRemoteData.toString().trim();
const fullCmd = `${zapExecutable()} init && ${zapExecutable()} remote set origin ${webURL}/.api/zap github.com/${zapRemote} && zap status -q`;
let origin = sp.spawn(fullCmd, [], { shell: true, cwd: vscode.workspace.rootPath });
origin.stdout.on("data", () => {
resolve(true);
});
origin.stderr.on("data", () => {
reject(false);
});
});
}));
});
}
exports.autoConfigureRemotes = autoConfigureRemotes;
// TODO: When @stephens changes are merged in we can use the default config instead of this. - @Kingy
function autoCheckoutRemoteBranch() {
return __awaiter(this, void 0, void 0, function* () {
return new Promise((resolve, reject) => {
setTimeout(() => {
let status = sp.spawn(zapExecutable(), ["status", "-q"], { cwd: vscode.workspace.rootPath });
status.stdout.on("data", (data) => {
let zapRemote = data.toString().trim();
const fullCmd = `${zapExecutable()} checkout -upstream origin -overwrite ${zapRemote} && zap remote -v`;
let checkout = sp.spawn(fullCmd, [], { shell: true, cwd: vscode.workspace.rootPath });
checkout.stdout.on("data", () => {
resolve();
});
checkout.stderr.on("data", (checkoutErr) => {
reject(checkoutErr);
});
});
status.stderr.on("data", (err) => {
reject(err);
});
}, 1000);
});
});
}
exports.autoCheckoutRemoteBranch = autoCheckoutRemoteBranch;
function startLocalServer() {
return __awaiter(this, void 0, void 0, function* () {
const socketPath = path.resolve(vscode.workspace.rootPath, vscode.workspace.getConfiguration("zap").get("localServer.socketPath"));
const isConnected = yield checkConnection();
if (isConnected) {
return;
}
const p = sp.spawn(zapExecutable(), ["server"]);
return new Promise((resolve, reject) => {
let exited = false;
let connected = false;
p.on("close", () => {
exited = true;
resolve();
});
// Wait until the client is ready.
const maxWaitMsec = 1000;
const deadline = Date.now() + maxWaitMsec;
const id = setInterval(() => {
if (exited) {
clearInterval(id);
return;
}
if (fs.existsSync(socketPath)) {
clearInterval(id);
connected = true;
return resolve();
}
if (Date.now() > deadline) {
clearInterval(id);
const msg = `couldn't connect to local Zap server at ${socketPath} within ${maxWaitMsec}ms`;
status_1.outputChannel.show();
status_1.outputChannel.appendLine(`FAILURE: ${msg}`);
exited = true;
setTimeout(() => p.kill(), 2000); // wait otherwise we miss out on stdout and stderr's 'data' events
reject(msg);
return;
}
}, 100);
});
});
}
exports.startLocalServer = startLocalServer;
function zapExecutable() {

@@ -60,2 +162,16 @@ const value = vscode.workspace.getConfiguration("zap").get("executable");

exports.zapExecutable = zapExecutable;
function checkConnection() {
return __awaiter(this, void 0, void 0, function* () {
const socketPath = path.resolve(vscode.workspace.rootPath, vscode.workspace.getConfiguration("zap").get("localServer.socketPath"));
return new Promise((resolve) => {
net.connect(socketPath)
.on("connect", () => {
resolve(true);
})
.on("error", () => {
return resolve(false);
});
});
});
}
//# sourceMappingURL=localServer.js.map

@@ -320,2 +320,8 @@ "use strict";

function subtract(a, a1) {
if (!a) {
throw new Error("no a");
}
if (!a1) {
throw new Error("no a1");
}
if (!a.edit) {

@@ -322,0 +328,0 @@ throw new Error("no a.edit");

@@ -27,6 +27,8 @@ "use strict";

this.item.show();
this.setStatus(Status.Starting);
if (!vscode.workspace.getConfiguration("zap").get("enable")) {
this.setStatus(Status.ServerUnavailable);
}
else {
this.setStatus(Status.Starting);
}
this.remoteClient.onDidChangeState((event) => {

@@ -56,3 +58,3 @@ exports.outputChannel.appendLine(`Status: ${client_1.State[event.oldState]} ⟶ ${client_1.State[event.newState]}`);

dispose() {
// noop
this.item.dispose();
}

@@ -64,3 +66,3 @@ setActiveRef(ref) {

if (data) {
if (data.branch) {
if (data.branch && data.branch !== "HEAD") {
this.lastBranch = data.branch;

@@ -71,14 +73,15 @@ }

case Status.Starting:
this.item.color = "";
this.item.text = "$(zap) $(ellipses)";
this.item.tooltip = "";
const branchText = this.lastBranch || "$(ellipses)";
this.item.color = "white";
this.item.text = `$(zap) ${branchText}`;
this.item.command = "zap.restart";
break;
case Status.ServerUnavailable:
this.item.color = "";
this.item.color = "red";
this.item.text = "$(zap) Off";
this.item.tooltip = "Start Zap and enable in workspace";
this.item.command = "zap.enableAndAddWorkspace";
this.item.tooltip = "Restart Zap";
this.item.command = "zap.restart";
break;
case Status.WorkspaceNotAddedOnServer:
this.item.color = "";
this.item.color = "white";
this.item.text = "$(zap) Off";

@@ -89,4 +92,4 @@ this.item.tooltip = "Enable Zap in this workspace";

case Status.OK:
this.item.color = ""; // default color
this.item.text = `$(zap) ${this.lastBranch}`;
this.item.color = "white"; // default color
this.item.text = `$(zap) ${this.lastBranch || "Select a Branch"}`;
this.item.tooltip = "";

@@ -97,8 +100,2 @@ // TODO(sqs): make this a menu with the choice to remove

break;
case Status.Running:
this.item.color = "white";
this.item.text = `$(zap) Select a Branch`;
this.item.tooltip = "";
this.item.command = "zap.ref.select";
break;
case Status.ServerWarning:

@@ -116,2 +113,8 @@ this.item.color = "yellow";

break;
case Status.Running:
this.item.color = "white";
this.item.text = `$(zap) Select a Branch`;
this.item.tooltip = "";
this.item.command = "zap.ref.select";
break;
}

@@ -118,0 +121,0 @@ this.item.show();

import * as vscode from "vscode";
export declare function activate(context: vscode.ExtensionContext): void;
export declare function openInBrowser(uri: vscode.Uri, sel: vscode.Selection | null, trackingEventName: "OpenFile" | "OpenAtCursor"): Promise<boolean | void>;
export declare function openInBrowser(uri: vscode.Uri, sel: vscode.Selection | null, trackingEventName: "OpenFile" | "OpenAtCursor"): Promise<boolean>;
export declare function openWorkspaceInBrowser(): Promise<void>;
"use strict";
var __assign = (this && this.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {

@@ -17,2 +25,3 @@ return new (P || (P = Promise))(function (resolve, reject) {

context.subscriptions.push(vscode.commands.registerTextEditorCommand("zap.web.openInBrowser.cursor", openAtCursor));
context.subscriptions.push(vscode.commands.registerCommand("zap.web.openWorkspaceInBrowser", openWorkspaceInBrowser));
}

@@ -33,18 +42,26 @@ exports.activate = activate;

// the repo (can use workspaceDirInRepo from vscode-sourcegraph).
return workspaceBrowserURL().then((identifier) => {
let url = `${identifier.url}/-/blob/${vscode.workspace.asRelativePath(uri)}?_event=${trackingEventName}&_source=${versionString()}&tmpZapRef=${identifier.ref}#${sel ? formatSelection(sel) : ""}`;
open(url);
return true;
});
}
exports.openInBrowser = openInBrowser;
function workspaceBrowserURL() {
return getRemoteRefID().then(remoteInfo => {
let url = vscode.workspace.getConfiguration("zap").get("web.url") +
"/${REPO}@${GITBRANCH}/-/blob/${PATH}${QUERY}#${LINE}"
"/${REPO}@${GITBRANCH}"
.replace("${REPO}", remoteInfo.repo)
.replace("${GITBRANCH}", remoteInfo.gitBranch)
.replace("${PATH}", vscode.workspace.asRelativePath(uri))
.replace("${QUERY}", `?_event=${trackingEventName}&_source=${versionString()}&tmpZapRef=${remoteInfo.ref}`)
.replace("${LINE}", sel ? formatSelection(sel) : "");
open(url);
return true;
.replace("${GITBRANCH}", remoteInfo.gitBranch);
return __assign({}, remoteInfo, { url });
}).catch(err => {
status_1.outputChannel.appendLine(`Error opening Web browser to URL: ${err}`);
vscode.window.showErrorMessage("Opening your Web browser failed.");
return null;
});
}
exports.openInBrowser = openInBrowser;
function openWorkspaceInBrowser() {
return workspaceBrowserURL().then((identifier) => open(`${identifier.url}?_event=openWorkspaceInBrowser&_source=${versionString()}&tmpZapRef=${identifier.ref}`));
}
exports.openWorkspaceInBrowser = openWorkspaceInBrowser;
// getRemoteRefID queries the server to find the remote ref for the

@@ -51,0 +68,0 @@ // current workspace's HEAD. This is necessary because (e.g.) the

@@ -5,3 +5,3 @@ {

"description": "WIP",
"version": "0.0.47",
"version": "0.0.48",
"publisher": "sqs",

@@ -42,3 +42,3 @@ "preview": true,

"dependencies": {
"libzap": "^0.0.47",
"libzap": "^0.0.48",
"open": "^0.0.5",

@@ -91,7 +91,2 @@ "vscode-jsonrpc": "3.0.1-alpha.7"

{
"command": "zap.enableAndAddWorkspace",
"title": "Zap: Start local server and enable in workspace",
"description": "Starts the local Zap server and enables Zap in this workspace."
},
{
"command": "zap.install",

@@ -102,2 +97,17 @@ "title": "Zap: Install/update client",

{
"command": "zap.localServer.start",
"title": "Zap: Starts the Local Server",
"description": "Starts the zap local server on the default socket path."
},
{
"command": "zap.branch.configureUpstream",
"title": "Zap: Configures upstream branch",
"description": "Configures the current Zap branch to have an upstream branch that it overwrites"
},
{
"command": "zap.workspace.configureOrigin",
"title": "Zap: Automatically configure remote 'origin'",
"description": "Sets the workspace's remote 'origin' to Sourcegraph.com"
},
{
"command": "zap.workspace.add",

@@ -123,2 +133,7 @@ "title": "Zap: Enable in workspace",

{
"command": "zap.web.openWorkspaceInBrowser",
"title": "⚡ Open Workspace in Web Browser",
"description": "Opens the current workspace in your Web browser."
},
{
"command": "zap.restart",

@@ -125,0 +140,0 @@ "title": "Restart Zap client",

import * as vscode from "vscode";
import { Client, ClientOptions, ServerOptions, State, StateChangeEvent } from "libzap/lib/remote/client";

@@ -8,2 +7,3 @@ import { Handler, MergeStrategy } from "libzap/lib/remote/handler";

import { Workspace } from "./workspace";
import { outputChannel } from "./status";

@@ -45,3 +45,2 @@ export class Controller {

this.client.registerHandler(Handler.id, this.handler);
// Reestablish watch and reattach workspace whenever we

@@ -71,16 +70,68 @@ // reconnect (and on the first time we connect)...

private attach(): Thenable<void> {
let mergeStrategy: MergeStrategy;
if (vscode.workspace.getConfiguration("zap").get<boolean>("overwrite")) {
mergeStrategy = MergeStrategy.LocalClobbersRemote;
} else {
mergeStrategy = MergeStrategy.RemoteClobbersLocal;
let mergeStrategy: MergeStrategy;
if (vscode.workspace.getConfiguration("zap").get<boolean>("overwrite")) {
mergeStrategy = MergeStrategy.LocalClobbersRemote;
} else {
mergeStrategy = MergeStrategy.RemoteClobbersLocal;
}
return this.handler.attachWorkspace({
repo: this.environment.repo,
ref: this.environment.zapRef,
}, this.workspace, mergeStrategy).then(() => null, (err) => {
console.error(`Error watching repo: ${err} ${err.stack}`);
});
}
private async autoCheckoutRemote(refInfo?: RefInfoResult): Promise<void> {
if (!refInfo) {
try {
refInfo = await this.queryRefInfo({ repo: vscode.workspace.rootPath!, ref: "HEAD" });
let web: vscode.MessageItem = { title: "Open" };
vscode.window.showInformationMessage("Open workspace on Sourcegraph", web).then(cb => {
if (cb === web) {
return vscode.commands.executeCommand("zap.web.openWorkspaceInBrowser");
}
});
vscode.window.setStatusBarMessage("Zap workspace configured", 5000);
} catch (err) {
outputChannel.show();
outputChannel.appendLine(`Error fetching workspace remote HEAD data - ${err}`);
}
}
}
return this.handler.attachWorkspace({
// This is used to automatically start the workspace when booting the extension.
public async autoStartWorkspace(): Promise<void> {
if (this.environment.zapRef !== "HEAD") {
return this.start();
}
try {
await vscode.commands.executeCommand("zap.localServer.start");
const didConfigure = await vscode.commands.executeCommand("zap.workspace.configureOrigin");
if (didConfigure) {
await vscode.commands.executeCommand("zap.branch.configureUpstream");
}
return this.start().then(async () => {
await this.autoCheckoutRemote();
return Promise.resolve();
}, async (err) => {
outputChannel.appendLine(`Could not connect to Zap Local Server. Attempting to Reconnect.`);
outputChannel.show();
return Promise.reject(err);
});
} catch (err) {
outputChannel.appendLine(`Error starting workspace: ${err}`);
}
}
private reset(mergeStrategy: MergeStrategy): Thenable<void> {
return this.handler.resetWorkspaceRefState({
repo: this.environment.repo,
ref: this.environment.zapRef,
}, this.workspace, mergeStrategy)
.then(() => null, (err) => {
console.error(`Error watching repo: ${err} ${err.stack}`);
});
}, this.workspace, mergeStrategy).then(() => null, (err) => {
console.error(`Error watching repo: ${err} ${err.stack}`);
});
}

@@ -123,3 +174,3 @@

for (const ref of refs) {
if (ref.repo === this.environment.repo) {
if (ref.repo === this.environment.repo && !ref.ref.startsWith("refs/remotes/")) {
let onSelect: Function | undefined = undefined;

@@ -131,11 +182,7 @@ let label = ref.ref;

}
if (ref.ref.startsWith("refs/remotes/")) {
label = "$(circle-slash) " + label;
onSelect = () => vscode.window.showErrorMessage("Switching to a remote-tracking Zap branch is not allowed.");
}
items.push({
label,
description: ref.target ? `$(arrow-right) ${ref.target}` : `${ref.rev} revisions $(git - branch) ${ref.gitBranch}@${ref.gitBase.slice(0, 6)} `,
detail: ref.watchers ? `Watchers: ${ref.watchers.join(" ")} ` : undefined,
description: ref.watchers ? `Watchers: ${ref.watchers.join(" ")} ` : "No current watchers",
detail: "Switch to this branch and start editing",
onSelect: onSelect ? onSelect : () => this.environment.zapRef = ref.ref,

@@ -145,2 +192,21 @@ });

}
if (this.environment.zapRef === "HEAD") {
items.push({
label: "$(x) Clobber Local Changes",
description: "Resets the zap state to match the remote state",
onSelect: () => {
this.reset(MergeStrategy.RemoteClobbersLocal);
},
});
items.push({
label: "$(x) Clobber Remote Changes",
description: "Overwrites the zap remote branch with your current state",
onSelect: () => {
this.reset(MergeStrategy.LocalClobbersRemote);
},
});
}
items.push({

@@ -147,0 +213,0 @@ label: "$(x) Turn Zap Off",

@@ -387,3 +387,3 @@ import * as path from "path";

return "warning";
case "":
case "white":
return "ok";

@@ -390,0 +390,0 @@ default:

@@ -39,3 +39,3 @@ import * as vscode from "vscode";

if (ref !== "HEAD") {
console.warn(`Attempting to set zap ref to ${ref} instead of HEAD which is currently unsupported in the extension`);
vscode.window.showWarningMessage(`Attempting to set Zap ref to ${ref} instead of HEAD, which is currently unsupported in the extension`);
return;

@@ -42,0 +42,0 @@ }

@@ -9,5 +9,3 @@ // This is the extension's shared entrypoint. All platforms call this

import { IEnvironment } from "./environment";
import { StatusHandler, outputChannel } from "./status";
import { ErrorCode } from "libzap/lib/remote/protocol";

@@ -39,4 +37,10 @@ export function activate(env: IEnvironment, ctx: vscode.ExtensionContext): Controller | null {

let shouldAutostart = !process.env.ZAP_E2E_NAME;
const updateEnabled = (enabled: boolean): void => {
if (enabled) {
if (shouldAutostart) {
controller.autoStartWorkspace();
shouldAutostart = false;
return;
}
startController(controller);

@@ -56,21 +60,2 @@ } else {

ctx.subscriptions.push(vscode.commands.registerCommand("zap.enableAndAddWorkspace", async () => {
try {
await vscode.workspace.getConfiguration("zap").update("enable", true, true);
await startController(controller);
// // We cannot actually attach to the env if we are running on Web right now.
// // HACK check for web.
// if (!isWebEnv() && isEnabled()) {
// await controller.client.sendRequest(WorkspaceAddRequest.type, { dir: vscode.workspace.rootPath } as WorkspaceAddParams);
// }
} catch (err) {
if ((err as any).code === ErrorCode.ErrorCodeWorkspaceExists) {
return;
}
outputChannel.appendLine(`Enabling Zap in this workspace failed: ${err}`);
outputChannel.show();
vscode.window.showErrorMessage("Enabling Zap in this workspace failed.");
}
}));
return controller;

@@ -86,12 +71,7 @@ }

export function isWebEnv(): boolean {
return process.env.NODE_ENV && !vscode.workspace.getConfiguration("zap").get<boolean>("_test") && !process.env.CI;
}
export function startController(controller: Controller): Thenable<void> {
return controller.start().then(() => { /* noop */ }, err => {
console.log(`Zap failed to start: ${err}`);
outputChannel.appendLine(`Zap failed to start: ${err}`);
outputChannel.show();
vscode.window.showErrorMessage(`Zap failed to start.`);
return controller.start().then(() => {
/* noop */
}, (err) => {
outputChannel.appendLine(`Error starting the controller: ${err}`);
});

@@ -102,4 +82,4 @@ };

return controller.stop().then(() => { /* noop */ }, err => {
console.error(`Zap failed to stop: ${err}`);
outputChannel.appendLine(`Zap failed to stop: ${err}`);
});
};

@@ -26,6 +26,10 @@ // This is the extension's entrypoint used by vscode. Things in here

ctx.subscriptions.push(vscode.commands.registerCommand("zap.install", () => zapLocalServer.install()));
ctx.subscriptions.push(vscode.commands.registerCommand("zap.localServer.start", () => zapLocalServer.startLocalServer()));
ctx.subscriptions.push(vscode.commands.registerCommand("zap.workspace.configureOrigin", () => zapLocalServer.autoConfigureRemotes()));
ctx.subscriptions.push(vscode.commands.registerCommand("zap.branch.configureUpstream", () => zapLocalServer.autoCheckoutRemoteBranch()));
activateWebExtension(ctx);
vscode.commands.executeCommand("zap.localServer.start");
return activateCommon(vscodeEnvironment, ctx);
}

@@ -5,2 +5,5 @@ import * as sp from "child_process";

import { outputChannel } from "./status";
import * as net from "net";
import * as fs from "fs";
import * as path from "path";

@@ -46,2 +49,90 @@ export function promptToInstall(): Promise<boolean> {

export async function autoConfigureRemotes(): Promise<boolean> {
return new Promise<boolean>(async (resolve, reject) => {
const ghRemote = sp.spawn(`git ls-remote --get-url | sed 's/.*://;s/.git$//'`, [], {
shell: true,
cwd: vscode.workspace.rootPath,
});
const webURL = vscode.workspace.getConfiguration("zap").get("web.url");
ghRemote.stdout.on("data", (ghRemoteData) => {
const zapRemote = ghRemoteData.toString().trim();
const fullCmd = `${zapExecutable()} init && ${zapExecutable()} remote set origin ${webURL}/.api/zap github.com/${zapRemote} && zap status -q`;
let origin = sp.spawn(fullCmd, [], {shell: true, cwd: vscode.workspace.rootPath});
origin.stdout.on("data", () => {
resolve(true);
});
origin.stderr.on("data", () => {
reject(false);
});
});
});
}
// TODO: When @stephens changes are merged in we can use the default config instead of this. - @Kingy
export async function autoCheckoutRemoteBranch(): Promise<void> {
return new Promise<void>((resolve, reject) => {
setTimeout(() => {
let status = sp.spawn(zapExecutable(), ["status", "-q"], {cwd: vscode.workspace.rootPath});
status.stdout.on("data", (data) => {
let zapRemote = data.toString().trim();
const fullCmd = `${zapExecutable()} checkout -upstream origin -overwrite ${zapRemote} && zap remote -v`;
let checkout = sp.spawn(fullCmd, [], { shell: true, cwd: vscode.workspace.rootPath });
checkout.stdout.on("data", () => {
resolve();
});
checkout.stderr.on("data", (checkoutErr) => {
reject(checkoutErr);
});
});
status.stderr.on("data", (err) => {
reject(err);
});
}, 1000);
});
}
export async function startLocalServer(): Promise<void> {
const socketPath = path.resolve(vscode.workspace.rootPath, vscode.workspace.getConfiguration("zap").get<string>("localServer.socketPath"));
const isConnected = await checkConnection();
if (isConnected) {
return;
}
const p = sp.spawn(zapExecutable(), ["server"]);
return new Promise<void>((resolve, reject) => {
let exited = false;
let connected = false;
p.on("close", () => {
exited = true;
resolve();
});
// Wait until the client is ready.
const maxWaitMsec = 1000;
const deadline = Date.now() + maxWaitMsec;
const id = setInterval(() => {
if (exited) {
clearInterval(id);
return;
}
if (fs.existsSync(socketPath)) {
clearInterval(id);
connected = true;
return resolve();
}
if (Date.now() > deadline) {
clearInterval(id);
const msg = `couldn't connect to local Zap server at ${socketPath} within ${maxWaitMsec}ms`;
outputChannel.show();
outputChannel.appendLine(`FAILURE: ${msg}`);
exited = true;
setTimeout(() => p.kill(), 2000); // wait otherwise we miss out on stdout and stderr's 'data' events
reject(msg);
return;
}
}, 100);
});
}
export function zapExecutable(): string {

@@ -54,1 +145,14 @@ const value = vscode.workspace.getConfiguration("zap").get<string>("executable");

}
async function checkConnection(): Promise<boolean> {
const socketPath = path.resolve(vscode.workspace.rootPath, vscode.workspace.getConfiguration("zap").get<string>("localServer.socketPath"));
return new Promise<boolean>((resolve) => {
net.connect(socketPath)
.on("connect", () => {
resolve(true);
})
.on("error", () => {
return resolve(false);
});
});
}

@@ -314,2 +314,8 @@ import * as vscode from "vscode";

export function subtract(a: WorkspaceOp, a1: WorkspaceOp): WorkspaceOp {
if (!a) {
throw new Error("no a");
}
if (!a1) {
throw new Error("no a1");
}
if (!a.edit) {

@@ -316,0 +322,0 @@ throw new Error("no a.edit");

@@ -39,6 +39,7 @@ import * as vscode from "vscode";

this.item.show();
this.setStatus(Status.Starting);
if (!vscode.workspace.getConfiguration("zap").get<boolean>("enable")) {
this.setStatus(Status.ServerUnavailable);
} else {
this.setStatus(Status.Starting);
}

@@ -71,3 +72,3 @@

public dispose(): void {
// noop
this.item.dispose();
}

@@ -81,3 +82,3 @@

if (data) {
if (data.branch) {
if (data.branch && data.branch !== "HEAD") {
this.lastBranch = data.branch;

@@ -89,16 +90,17 @@ }

case Status.Starting:
this.item.color = "";
this.item.text = "$(zap) $(ellipses)";
this.item.tooltip = "";
const branchText = this.lastBranch || "$(ellipses)";
this.item.color = "white";
this.item.text = `$(zap) ${branchText}`;
this.item.command = "zap.restart";
break;
case Status.ServerUnavailable:
this.item.color = "";
this.item.color = "red";
this.item.text = "$(zap) Off";
this.item.tooltip = "Start Zap and enable in workspace";
this.item.command = "zap.enableAndAddWorkspace";
this.item.tooltip = "Restart Zap";
this.item.command = "zap.restart";
break;
case Status.WorkspaceNotAddedOnServer:
this.item.color = "";
this.item.color = "white";
this.item.text = "$(zap) Off";

@@ -110,4 +112,4 @@ this.item.tooltip = "Enable Zap in this workspace";

case Status.OK:
this.item.color = ""; // default color
this.item.text = `$(zap) ${this.lastBranch!}`;
this.item.color = "white"; // default color
this.item.text = `$(zap) ${this.lastBranch || "Select a Branch"}`;
this.item.tooltip = "";

@@ -119,9 +121,2 @@ // TODO(sqs): make this a menu with the choice to remove

case Status.Running:
this.item.color = "white";
this.item.text = `$(zap) Select a Branch`;
this.item.tooltip = "";
this.item.command = "zap.ref.select";
break;
case Status.ServerWarning:

@@ -140,3 +135,11 @@ this.item.color = "yellow";

break;
case Status.Running:
this.item.color = "white";
this.item.text = `$(zap) Select a Branch`;
this.item.tooltip = "";
this.item.command = "zap.ref.select";
break;
}
this.item.show();

@@ -143,0 +146,0 @@ }

@@ -13,2 +13,3 @@ import * as fs from "fs";

context.subscriptions.push(vscode.commands.registerTextEditorCommand("zap.web.openInBrowser.cursor", openAtCursor));
context.subscriptions.push(vscode.commands.registerCommand("zap.web.openWorkspaceInBrowser", openWorkspaceInBrowser));
}

@@ -31,19 +32,27 @@

// the repo (can use workspaceDirInRepo from vscode-sourcegraph).
return workspaceBrowserURL().then((identifier) => {
let url = `${identifier.url}/-/blob/${vscode.workspace.asRelativePath(uri)}?_event=${trackingEventName}&_source=${versionString()}&tmpZapRef=${identifier.ref}#${ sel ? formatSelection(sel) : ""}`;
open(url);
return true;
});
}
function workspaceBrowserURL(): Promise<RefIdentifier & { gitBranch: string; url: string }> {
return getRemoteRefID().then(remoteInfo => {
let url = vscode.workspace.getConfiguration("zap").get<string>("web.url") +
"/${REPO}@${GITBRANCH}/-/blob/${PATH}${QUERY}#${LINE}"
"/${REPO}@${GITBRANCH}"
.replace("${REPO}", remoteInfo.repo)
.replace("${GITBRANCH}", remoteInfo.gitBranch)
.replace("${PATH}", vscode.workspace.asRelativePath(uri))
.replace("${QUERY}", `?_event=${trackingEventName}&_source=${versionString()}&tmpZapRef=${remoteInfo.ref}`)
.replace("${LINE}", sel ? formatSelection(sel) : "");
open(url);
return true;
.replace("${GITBRANCH}", remoteInfo.gitBranch);
return {...remoteInfo, url };
}).catch(err => {
outputChannel.appendLine(`Error opening Web browser to URL: ${err}`);
vscode.window.showErrorMessage("Opening your Web browser failed.");
return null;
});
}
export function openWorkspaceInBrowser() {
return workspaceBrowserURL().then((identifier) => open(`${identifier.url}?_event=openWorkspaceInBrowser&_source=${versionString()}&tmpZapRef=${identifier.ref}`));
}
// getRemoteRefID queries the server to find the remote ref for the

@@ -50,0 +59,0 @@ // current workspace's HEAD. This is necessary because (e.g.) the

@@ -194,3 +194,3 @@ import * as vscode from "vscode";

for (const [uri] of edit.entries()) {
const file: string = this.environment.asRelativePathInsideWorkspace(uri) !;
const file: string = this.environment.asRelativePathInsideWorkspace(uri)!;
this.documentIsDirty.set(uri.toString(), this.documentIsDirty.get(uri.toString()) || Boolean(op.edit![`#${file}`]));

@@ -236,3 +236,3 @@ }

for (const doc of vscode.workspace.textDocuments) {
const fileName: string = this.environment.asRelativePathInsideWorkspace(doc.uri) !;
const fileName: string = this.environment.asRelativePathInsideWorkspace(doc.uri)!;
if (fileName !== null && edit.has(doc.uri) && !op.edit![`#${fileName}`]) {

@@ -239,0 +239,0 @@ if (!await doc.save()) {

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc