Skip to content

Commit

Permalink
first commit
Browse files Browse the repository at this point in the history
  • Loading branch information
GabiG committed Dec 17, 2016
0 parents commit 5e28cb3
Show file tree
Hide file tree
Showing 16 changed files with 492 additions and 0 deletions.
12 changes: 12 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
root = true

[*]
indent_style = tab
indent_size = 3
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

[*.md]
trim_trailing_whitespace = false
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
out
node_modules
28 changes: 28 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// A launch configuration that compiles the extension and then opens it inside a new window
{
"version": "0.1.0",
"configurations": [
{
"name": "Launch Extension",
"type": "extensionHost",
"request": "launch",
"runtimeExecutable": "${execPath}",
"args": ["--extensionDevelopmentPath=${workspaceRoot}" ],
"stopOnEntry": false,
"sourceMaps": true,
"outFiles": [ "${workspaceRoot}/out/src/**/*.js" ],
"preLaunchTask": "npm"
},
{
"name": "Launch Tests",
"type": "extensionHost",
"request": "launch",
"runtimeExecutable": "${execPath}",
"args": ["--extensionDevelopmentPath=${workspaceRoot}", "--extensionTestsPath=${workspaceRoot}/out/test" ],
"stopOnEntry": false,
"sourceMaps": true,
"outFiles": [ "${workspaceRoot}/out/test/**/*.js" ],
"preLaunchTask": "npm"
}
]
}
10 changes: 10 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// Place your settings in this file to overwrite default and user settings.
{
"files.exclude": {
"out": false // set this to true to hide the "out" folder with the compiled JS files
},
"search.exclude": {
"out": true // set this to false to include "out" folder in search results
},
"typescript.tsdk": "./node_modules/typescript/lib" // we want to use the TS server from our node_modules folder to control its version
}
30 changes: 30 additions & 0 deletions .vscode/tasks.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// Available variables which can be used inside of strings.
// ${workspaceRoot}: the root folder of the team
// ${file}: the current opened file
// ${fileBasename}: the current opened file's basename
// ${fileDirname}: the current opened file's dirname
// ${fileExtname}: the current opened file's extension
// ${cwd}: the current working directory of the spawned process

// A task runner that calls a custom npm script that compiles the extension.
{
"version": "0.1.0",

// we want to run npm
"command": "npm",

// the command is a shell script
"isShellCommand": true,

// show the output window only if unrecognized errors occur.
"showOutput": "silent",

// we run the custom script "compile" as defined in package.json
"args": ["run", "compile", "--loglevel", "silent"],

// The tsc compiler is started in watching mode
"isWatching": true,

// use the standard tsc in watch mode problem matcher to find compile problems in the output.
"problemMatcher": "$tsc-watch"
}
9 changes: 9 additions & 0 deletions .vscodeignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
.vscode/**
.vscode-test/**
out/test/**
test/**
src/**
**/*.map
.gitignore
tsconfig.json
vsc-extension-quickstart.md
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Change Log
All notable changes to the "auto-run-command" extension will be documented in this file.

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

## [Unreleased]
- Initial release
65 changes: 65 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
# auto-run-command README

This is the README for your extension "auto-run-command". After writing up a brief description, we recommend including the following sections.

This comment has been minimized.

Copy link
@oshalygin

oshalygin Jan 23, 2017

Contributor

Consider customizing this :)


## Features

Describe specific features of your extension including screenshots of your extension in action. Image paths are relative to this README file.

For example if there is an image subfolder under your extension project workspace:

\!\[feature X\]\(images/feature-x.png\)

> Tip: Many popular extensions utilize animations. This is an excellent way to show off your extension! We recommend short, focused animations that are easy to follow.
## Requirements

If you have any requirements or dependencies, add a section describing those and how to install and configure them.

## Extension Settings

Include if your extension adds any VS Code settings through the `contributes.configuration` extension point.

For example:

This extension contributes the following settings:

* `myExtension.enable`: enable/disable this extension
* `myExtension.thing`: set to `blah` to do something

## Known Issues

Calling out known issues can help limit users opening duplicate issues against your extension.

## Release Notes

Users appreciate release notes as you update your extension.

### 1.0.0

Initial release of ...

### 1.0.1

Fixed issue #.

### 1.1.0

Added features X, Y, and Z.

-----------------------------------------------------------------------------------------------------------

## Working with Markdown

**Note:** You can author your README using Visual Studio Code. Here are some useful editor keyboard shortcuts:

* Split the editor (`Cmd+\` on OSX or `Ctrl+\` on Windows and Linux)
* Toggle preview (`Shift+CMD+V` on OSX or `Shift+Ctrl+V` on Windows and Linux)
* Press `Ctrl+Space` (Windows, Linux) or `Cmd+Space` (OSX) to see a list of Markdown snippets

### For more information

* [Visual Studio Code's Markdown Support](http://code.visualstudio.com/docs/languages/markdown)
* [Markdown Syntax Reference](https://help.github.com/articles/markdown-basics/)

**Enjoy!**
71 changes: 71 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
{
"name": "auto-run-command",
"displayName": "Auto Run Command",
"description": "Run a vscode on project init. Made to run wallaby.js automatically when a project is opened",
"version": "0.0.1",
"publisher": "gabrielgrinberg",
"engines": {
"vscode": "^1.5.0"
},
"categories": [
"Other"
],
"activationEvents": [
"*"
],
"main": "./out/src/extension",
"contributes": {
"commands": [{
"command": "auto-run-command.placeholder-command",
"title": "Auto Run Command Placeholder"
}],
"configuration": {
"title": "Auto Run Command config",
"description": "",
"type": "object",
"properties": {
"auto-run-command.rules": {
"type": "array",
"title": "Auto Run Command Rules",
"default": [
{
"condition": "always",
"command": "auto-run-command.placeholder-command",
"message": "Running a dummy command"
}
],
"items": {
"type": "object",
"properties": {
"command": {
"type": ["string", "array"],
"description": "Command to run when the rule is matched"
},
"condition": {
"type": ["string", "array"],
"description": "Condition to match against. See documentation for possible condition"
},
"message": {
"type": "string",
"description": "A descriptive message to show when the condition is met. Defaults to the robotic condition text"
}
}
}
}
}
}
},
"scripts": {
"vscode:prepublish": "tsc -p ./",
"compile": "tsc -watch -p ./",
"postinstall": "node ./node_modules/vscode/bin/install",
"test": "node ./node_modules/vscode/bin/test"
},
"devDependencies": {
"typescript": "^2.0.3",
"vscode": "^1.0.0",
"mocha": "^2.3.3",
"@types/node": "^6.0.40",
"@types/mocha": "^2.2.32"
}
}
67 changes: 67 additions & 0 deletions src/extension.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { checkCondition } from './lib/condition-checker';
import { parseCondition } from './lib/condition-parser';

import * as vscode from 'vscode';

const nameSpace = 'auto-run-command';

interface Rule {
command: string | string[];
condition: string | string [];
message?: string;
}

interface Config {
rules: Rule[];
}

export function activate(context: vscode.ExtensionContext) {

let disposable = vscode.commands.registerCommand(`${nameSpace}.placeholder-command`, () => {

This comment has been minimized.

Copy link
@oshalygin

oshalygin Jan 23, 2017

Contributor

this is never reassigned, consider using const disposable

vscode.window.showInformationMessage('Auto run command is working. Checkout the README to make it do something useful!');
});

context.subscriptions.push(disposable);

const nsConfig = vscode.workspace.getConfiguration(nameSpace);
const rules = nsConfig.get('rules') as Rule[];


const runCommandDelayed = (command: string, message: string) => {

const safetyDelay = 5000; //to ensure other extensions got their moves on

This comment has been minimized.

Copy link
@david-pe

david-pe Jan 23, 2017

In the readme you asked for a better way to safely use a different extension ...
So maybe instead of a constant delay you could ask for dependencies in the config and then poll a different extension like this
vscode.extensions.getExtension('WallabyJs.wallaby-vscode').isActive


setTimeout(() => {
vscode.commands.executeCommand(command)
.then(
() => vscode.window.showInformationMessage(`[Auto Run Command] Condition met - ${message}`),
(reason) => vscode.window.showErrorMessage(`[Auto Run Command] Condition met but command [${command}] raised an error - [${reason}] `)
);
}, safetyDelay);
};

rules.forEach(rule => {
console.log(rule);
const conditions: string[] = typeof rule.condition === 'string' ? [rule.condition] : rule.condition || [];
const commands: string[] = typeof rule.command === 'string' ? [rule.command] : rule.command || [];
const message = rule.message || conditions.join(' and ');

try {
const parsed = conditions.map(parseCondition);
const checkPromises = parsed.map(checkCondition);
return Promise.all(checkPromises)
.then(values => {
if (values.every(id => !!id)) {
commands.forEach(cmd => runCommandDelayed(cmd, message));
}
});
} catch (e) {
vscode.window.showErrorMessage(`[Auto Run Command] ${e}`);
}
});
}

// this method is called when your extension is deactivated
export function deactivate() {
//console.
}
23 changes: 23 additions & 0 deletions src/lib/condition-checker.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { ParsedCondition, ParsedConditionType} from './condition-parser';
import * as vscode from 'vscode';

export const checkCondition = async (rule: ParsedCondition): Promise<boolean> => {
const args = rule.args;
const editor = vscode.window.activeTextEditor;

switch (rule.type) {

This comment has been minimized.

Copy link
@oshalygin

oshalygin Jan 23, 2017

Contributor

consider adding a default case

case ParsedConditionType.always:
return true;
case ParsedConditionType.isLanguage:
return editor && editor.document.languageId === args[0];
case ParsedConditionType.hasFile:
const results = await vscode.workspace.findFiles(args[0], '', 1);
return results.length > 0;
case ParsedConditionType.isRootFolder:
const rootPath = vscode.workspace.rootPath || '';
const folderMatches = rootPath.match(/([^\/]*)\/*$/);
const match = folderMatches && folderMatches[1];
return match && match === args[0];
}
};

48 changes: 48 additions & 0 deletions src/lib/condition-parser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
export enum ParsedConditionType {
always = 1,
hasFile = 2,
isLanguage = 3,
isRootFolder = 4
}

export type ParsedCondition = {type: ParsedConditionType, args: string[]};

class AmbiguousRuleError extends Error {};
class UnknownRuleError extends Error {};

export const parseCondition = (rule: string): ParsedCondition => {

const ruleMatchers = [
{
pattern: /^always$/,
type: ParsedConditionType.always
},
{
pattern: /^hasFile:\s*([^\s]+)\s*/,
type: ParsedConditionType.hasFile
},
{
pattern: /isLanguage:\s*([^\s]+)\s*/,
type: ParsedConditionType.isLanguage
},
{
pattern: /isRootFolder:\s*([^\s]+)\s*/,
type: ParsedConditionType.isRootFolder
}
];

const matchedRules = ruleMatchers.filter(matcher => rule.match(matcher.pattern));

if (matchedRules.length > 1) {
throw new AmbiguousRuleError('Please open an issue. ');
} else if (matchedRules.length === 0) {
throw new UnknownRuleError(`Unable to parse rule - [${rule}], please make sure you are using a known rule pattern`);
} else {
const matchedRule = matchedRules[0];
const [firstMatch, ...tailMatches] = rule.match(matchedRule.pattern);
return {
type: matchedRule.type,
args: tailMatches.map(arg => arg.toString())
};
};
};
Loading

0 comments on commit 5e28cb3

Please sign in to comment.