1
1
mirror of https://github.com/kahole/edamagit.git synced 2024-09-11 07:15:31 +03:00

inital chaos

This commit is contained in:
kahole 2019-12-02 22:50:08 +01:00
commit eb6b23948f
16 changed files with 1818 additions and 0 deletions

5
.gitignore vendored Normal file
View File

@ -0,0 +1,5 @@
out
node_modules
.vscode-test/
*.vsix
.vscode

10
.vscodeignore Normal file
View File

@ -0,0 +1,10 @@
.vscode/**
.vscode-test/**
out/test/**
src/**
.gitignore
vsc-extension-quickstart.md
**/tsconfig.json
**/tslint.json
**/*.map
**/*.ts

9
CHANGELOG.md Normal file
View File

@ -0,0 +1,9 @@
# Change Log
All notable changes to the "magit" 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
README.md Normal file
View File

@ -0,0 +1,65 @@
# magit README
This is the README for your extension "magit". After writing up a brief description, we recommend including the following sections.
## 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 macOS or `Ctrl+\` on Windows and Linux)
* Toggle preview (`Shift+CMD+V` on macOS or `Shift+Ctrl+V` on Windows and Linux)
* Press `Ctrl+Space` (Windows, Linux) or `Cmd+Space` (macOS) 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!**

1030
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

42
package.json Normal file
View File

@ -0,0 +1,42 @@
{
"name": "magit",
"displayName": "magit",
"description": "Magit for VSCode",
"version": "0.0.1",
"engines": {
"vscode": "^1.40.0"
},
"categories": [
"Other"
],
"activationEvents": [
"onCommand:extension.magit"
],
"main": "./out/extension.js",
"contributes": {
"commands": [
{
"command": "extension.magit",
"title": "Magit Status"
}
]
},
"scripts": {
"vscode:prepublish": "npm run compile",
"compile": "tsc -p ./",
"watch": "tsc -watch -p ./",
"pretest": "npm run compile",
"test": "node ./out/test/runTest.js"
},
"devDependencies": {
"@types/glob": "^7.1.1",
"@types/mocha": "^5.2.7",
"@types/node": "^12.11.7",
"@types/vscode": "^1.40.0",
"glob": "^7.1.5",
"mocha": "^6.2.2",
"typescript": "^3.6.4",
"tslint": "^5.20.0",
"vscode-test": "^1.2.2"
}
}

133
src/extension.ts Normal file
View File

@ -0,0 +1,133 @@
// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import { workspace, languages, window, extensions, commands, ExtensionContext, Disposable, ViewColumn, FileChangeType } from 'vscode';
import ContentProvider, { encodeLocation } from './provider';
import { API as GitAPI, GitExtension, APIState, Status } from './typings/git';
// https://github.com/microsoft/vscode/blob/f667462a2a8a12c92dbcdd8acf92df7354063691/extensions/git/src/util.ts#L309
import { dirname, sep } from 'path';
function isWindowsPath(path: string): boolean {
return /^[a-zA-Z]:\\/.test(path);
}
function isDescendant(parent: string, descendant: string): boolean {
if (parent === descendant) {
return true;
}
if (parent.charAt(parent.length - 1) !== sep) {
parent += sep;
}
// Windows is case insensitive
if (isWindowsPath(parent)) {
parent = parent.toLowerCase();
descendant = descendant.toLowerCase();
}
return descendant.startsWith(parent);
}
//------------------------------------
export function activate(context: ExtensionContext) {
// How to
// Use existing tooling as much as possible
// make magit, but the fancy stuff should be vscode like
// BIGGEST CHALLENGE RN
// Git: either use vscode.git or run commands and "parse"
// Nice example:
// https://github.com/DonJayamanne/gitHistoryVSCode/blob/master/src/adapter/exec/gitCommandExec.ts
// Git extension API
// https://github.com/microsoft/vscode/blob/master/extensions/git/src/api/api1.ts
// Svakt, men exposer git executable
// Language:
// Custom keybindings for buffer: define a language mode
// language is activated based on file ending in uri, so .magit from provider.ts
// Transient interface:
// Key presses: https://github.com/lucax88x/CodeAceJumper/blob/master/src/inline-input.ts#L81
//Command pallete
// When a command should be available: https://code.visualstudio.com/api/extension-guides/command#controlling-when-a-command-shows-up-in-the-command-palette
// https://code.visualstudio.com/api/extension-guides/command#enablement-of-commands
// Dynamic selection, filter with executeCommand("workbench.action.quickOpen", ">commandPREFIX");
// Helm like branch selector: QuickPick https://code.visualstudio.com/api/references/vscode-api#QuickInput
// window.showQuickPick(repository.state.refs.map( r => r.name!));
// repository.checkout(branch.name)
// Name stuff: InputBox
// Diff: language mode "diff"
// Commit message: language mode "git-commit message"
// should just open buffer. Git supports this out of the box, like when it opens $EDITOR
// Folding: https://code.visualstudio.com/api/references/vscode-api#languages.registerFoldingRangeProvider
// Register <tab> for folding for the language mode!
// { "key": "tab", "command": "cursorHome", "when": "mightBeUseful to have when
// Status bar message for git feedback stuff
// Erorrs: show ErrorMessage for feil
// VsVim:
// Needs to work well with VsVim as well
if (workspace.workspaceFolders && workspace.workspaceFolders[0]) {
let gitExtension = extensions.getExtension<GitExtension>('vscode.git')!.exports;
const gitApi = gitExtension.getAPI(1);
const rootPath = workspace.workspaceFolders[0].uri.fsPath;
console.log(rootPath);
const repository = gitApi.repositories.filter(r => isDescendant(r.rootUri.fsPath, rootPath))[0];
// repository.diff()
repository.status()
.then(console.log)
.then(() => {
//console.log(repository.state.indexChanges);
console.log(repository.state.HEAD);
console.log(repository.state.remotes);
console.log(repository.state.refs)
console.log(repository.state.workingTreeChanges)
});
const provider = new ContentProvider(repository);
const providerRegistrations = Disposable.from(
workspace.registerTextDocumentContentProvider(ContentProvider.scheme, provider)
);
let disposable = commands.registerCommand('extension.magit', async () => {
const uri = encodeLocation("gitstatus");
workspace.openTextDocument(uri).then(doc => window.showTextDocument(doc, ViewColumn.Beside));
//return commands.executeCommand("workbench.action.quickOpen", ">bdd/halla");
// window.showInputBox({prompt: "Name of your branch or whatever"});
});
context.subscriptions.push(
provider,
providerRegistrations,
disposable
);
}
}
// this method is called when your extension is deactivated
export function deactivate() { }

80
src/provider.ts Normal file
View File

@ -0,0 +1,80 @@
import * as vscode from 'vscode';
import StatusDocument from './statusDocument';
import { Repository } from './typings/git';
export default class Provider implements vscode.TextDocumentContentProvider {
static scheme = 'magit';
private _onDidChange = new vscode.EventEmitter<vscode.Uri>();
private _documents = new Map<string, StatusDocument>();
private _editorDecoration = vscode.window.createTextEditorDecorationType({ textDecoration: 'underline' });
private _subscriptions: vscode.Disposable;
public repository: Repository;
constructor(repository: Repository) {
this.repository = repository;
// Listen to the `closeTextDocument`-event which means we must
// clear the corresponding model object - `ReferencesDocument`
this._subscriptions = vscode.workspace.onDidCloseTextDocument(doc => this._documents.delete(doc.uri.toString()));
}
dispose() {
this._subscriptions.dispose();
this._documents.clear();
this._editorDecoration.dispose();
this._onDidChange.dispose();
}
// Expose an event to signal changes of _virtual_ documents
// to the editor
get onDidChange() {
return this._onDidChange.event;
}
// Provider method that takes an uri of the `references`-scheme and
// resolves its content by (1) running the reference search command
// and (2) formatting the results
provideTextDocumentContent(uri: vscode.Uri): string | Thenable<string> {
// already loaded?
// let document = this._documents.get(uri.toString());
// if (document) {
// return document.value;
// }
// Decode target-uri and target-position from the provided uri and execute the
// `reference provider` command (https://code.visualstudio.com/api/references/commands).
// From the result create a references document which is in charge of loading,
// printing, and formatting references
let document = new StatusDocument(uri, this.repository, this._onDidChange);
this._documents.set(uri.toString(), document);
return document.value;
}
// provideDocumentLinks(document: vscode.TextDocument, token: vscode.CancellationToken): vscode.DocumentLink[] | undefined {
// // While building the virtual document we have already created the links.
// // Those are composed from the range inside the document and a target uri
// // to which they point
// const doc = this._documents.get(document.uri.toString());
// if (doc) {
// return doc.links;
// }
// }
}
let seq = 0;
export function encodeLocation(uri: string): vscode.Uri {
const query = uri;
return vscode.Uri.parse(`${Provider.scheme}:status.magit?${query}#${seq++}`);
}
export function decodeLocation(uri: vscode.Uri): [vscode.Uri, vscode.Position] {
let [target, line, character] = <[string, number, number]>JSON.parse(uri.query);
return [vscode.Uri.parse(target), new vscode.Position(line, character)];
}

46
src/statusDocument.ts Normal file
View File

@ -0,0 +1,46 @@
import * as vscode from 'vscode';
import { Repository } from './typings/git';
export default class StatusDocument {
private readonly _uri: vscode.Uri;
private readonly _emitter: vscode.EventEmitter<vscode.Uri>;
private readonly _lines: string[];
constructor(uri: vscode.Uri, repository: Repository, emitter: vscode.EventEmitter<vscode.Uri>) {
this._uri = uri;
// The ReferencesDocument has access to the event emitter from
// the containg provider. This allows it to signal changes
this._emitter = emitter;
// Start with printing a header and start resolving
this._lines = [];
this._lines.push(`Head: ${repository.state.HEAD!.name} ${repository.state.HEAD!.commit!}`);
this._lines.push('');
this._lines.push(`Unstaged changes (${repository.state.workingTreeChanges.length})`);
let unstagedFiles = repository.state.workingTreeChanges
.map(change => {
return change.uri.toString() + "";
});
this._lines.push(...unstagedFiles);
repository.log({ maxEntries: 10 })
.then(commits => {
let recentCommits = commits.map(commit =>
`${commit.hash.slice(0, 5)} ${commit.message}`);
this._lines.push(`Recent commits`);
this._lines.push(...recentCommits);
});
}
get value() {
return this._lines.join('\n');
}
}

23
src/test/runTest.ts Normal file
View File

@ -0,0 +1,23 @@
import * as path from 'path';
import { runTests } from 'vscode-test';
async function main() {
try {
// The folder containing the Extension Manifest package.json
// Passed to `--extensionDevelopmentPath`
const extensionDevelopmentPath = path.resolve(__dirname, '../../');
// The path to test runner
// Passed to --extensionTestsPath
const extensionTestsPath = path.resolve(__dirname, './suite/index');
// Download VS Code, unzip it and run the integration test
await runTests({ extensionDevelopmentPath, extensionTestsPath });
} catch (err) {
console.error('Failed to run tests');
process.exit(1);
}
}
main();

View File

@ -0,0 +1,15 @@
import * as assert from 'assert';
// You can import and use all API from the 'vscode' module
// as well as import your extension to test it
import * as vscode from 'vscode';
// import * as myExtension from '../extension';
suite('Extension Test Suite', () => {
vscode.window.showInformationMessage('Start all tests.');
test('Sample test', () => {
assert.equal(-1, [1, 2, 3].indexOf(5));
assert.equal(-1, [1, 2, 3].indexOf(0));
});
});

37
src/test/suite/index.ts Normal file
View File

@ -0,0 +1,37 @@
import * as path from 'path';
import * as Mocha from 'mocha';
import * as glob from 'glob';
export function run(): Promise<void> {
// Create the mocha test
const mocha = new Mocha({
ui: 'tdd',
});
mocha.useColors(true);
const testsRoot = path.resolve(__dirname, '..');
return new Promise((c, e) => {
glob('**/**.test.js', { cwd: testsRoot }, (err, files) => {
if (err) {
return e(err);
}
// Add files to the test suite
files.forEach(f => mocha.addFile(path.resolve(testsRoot, f)));
try {
// Run the mocha test
mocha.run(failures => {
if (failures > 0) {
e(new Error(`${failures} tests failed.`));
} else {
c();
}
});
} catch (err) {
e(err);
}
});
});
}

245
src/typings/git.d.ts vendored Normal file
View File

@ -0,0 +1,245 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Uri, SourceControlInputBox, Event, CancellationToken } from 'vscode';
export interface Git {
readonly path: string;
}
export interface InputBox {
value: string;
}
export const enum RefType {
Head,
RemoteHead,
Tag
}
export interface Ref {
readonly type: RefType;
readonly name?: string;
readonly commit?: string;
readonly remote?: string;
}
export interface UpstreamRef {
readonly remote: string;
readonly name: string;
}
export interface Branch extends Ref {
readonly upstream?: UpstreamRef;
readonly ahead?: number;
readonly behind?: number;
}
export interface Commit {
readonly hash: string;
readonly message: string;
readonly parents: string[];
readonly authorEmail?: string | undefined;
}
export interface Submodule {
readonly name: string;
readonly path: string;
readonly url: string;
}
export interface Remote {
readonly name: string;
readonly fetchUrl?: string;
readonly pushUrl?: string;
readonly isReadOnly: boolean;
}
export const enum Status {
INDEX_MODIFIED,
INDEX_ADDED,
INDEX_DELETED,
INDEX_RENAMED,
INDEX_COPIED,
MODIFIED,
DELETED,
UNTRACKED,
IGNORED,
INTENT_TO_ADD,
ADDED_BY_US,
ADDED_BY_THEM,
DELETED_BY_US,
DELETED_BY_THEM,
BOTH_ADDED,
BOTH_DELETED,
BOTH_MODIFIED
}
export interface Change {
/**
* Returns either `originalUri` or `renameUri`, depending
* on whether this change is a rename change. When
* in doubt always use `uri` over the other two alternatives.
*/
readonly uri: Uri;
readonly originalUri: Uri;
readonly renameUri: Uri | undefined;
readonly status: Status;
}
export interface RepositoryState {
readonly HEAD: Branch | undefined;
readonly refs: Ref[];
readonly remotes: Remote[];
readonly submodules: Submodule[];
readonly rebaseCommit: Commit | undefined;
readonly mergeChanges: Change[];
readonly indexChanges: Change[];
readonly workingTreeChanges: Change[];
readonly onDidChange: Event<void>;
}
export interface RepositoryUIState {
readonly selected: boolean;
readonly onDidChange: Event<void>;
}
/**
* Log options.
*/
export interface LogOptions {
/** Max number of log entries to retrieve. If not specified, the default is 32. */
readonly maxEntries?: number;
}
export interface Repository {
readonly rootUri: Uri;
readonly inputBox: InputBox;
readonly state: RepositoryState;
readonly ui: RepositoryUIState;
getConfigs(): Promise<{ key: string; value: string; }[]>;
getConfig(key: string): Promise<string>;
setConfig(key: string, value: string): Promise<string>;
getGlobalConfig(key: string): Promise<string>;
getObjectDetails(treeish: string, path: string): Promise<{ mode: string, object: string, size: number }>;
detectObjectType(object: string): Promise<{ mimetype: string, encoding?: string }>;
buffer(ref: string, path: string): Promise<Buffer>;
show(ref: string, path: string): Promise<string>;
getCommit(ref: string): Promise<Commit>;
clean(paths: string[]): Promise<void>;
apply(patch: string, reverse?: boolean): Promise<void>;
diff(cached?: boolean): Promise<string>;
diffWithHEAD(): Promise<Change[]>;
diffWithHEAD(path: string): Promise<string>;
diffWith(ref: string): Promise<Change[]>;
diffWith(ref: string, path: string): Promise<string>;
diffIndexWithHEAD(): Promise<Change[]>;
diffIndexWithHEAD(path: string): Promise<string>;
diffIndexWith(ref: string): Promise<Change[]>;
diffIndexWith(ref: string, path: string): Promise<string>;
diffBlobs(object1: string, object2: string): Promise<string>;
diffBetween(ref1: string, ref2: string): Promise<Change[]>;
diffBetween(ref1: string, ref2: string, path: string): Promise<string>;
hashObject(data: string): Promise<string>;
createBranch(name: string, checkout: boolean, ref?: string): Promise<void>;
deleteBranch(name: string, force?: boolean): Promise<void>;
getBranch(name: string): Promise<Branch>;
setBranchUpstream(name: string, upstream: string): Promise<void>;
getMergeBase(ref1: string, ref2: string): Promise<string>;
status(): Promise<void>;
checkout(treeish: string): Promise<void>;
addRemote(name: string, url: string): Promise<void>;
removeRemote(name: string): Promise<void>;
fetch(remote?: string, ref?: string, depth?: number): Promise<void>;
pull(unshallow?: boolean): Promise<void>;
push(remoteName?: string, branchName?: string, setUpstream?: boolean): Promise<void>;
blame(path: string): Promise<string>;
log(options?: LogOptions): Promise<Commit[]>;
}
export type APIState = 'uninitialized' | 'initialized';
export interface API {
readonly state: APIState;
readonly onDidChangeState: Event<APIState>;
readonly git: Git;
readonly repositories: Repository[];
readonly onDidOpenRepository: Event<Repository>;
readonly onDidCloseRepository: Event<Repository>;
toGitUri(uri: Uri, ref: string): Uri;
}
export interface GitExtension {
readonly enabled: boolean;
readonly onDidChangeEnablement: Event<boolean>;
/**
* Returns a specific API version.
*
* Throws error if git extension is disabled. You can listed to the
* [GitExtension.onDidChangeEnablement](#GitExtension.onDidChangeEnablement) event
* to know when the extension becomes enabled/disabled.
*
* @param version Version number.
* @returns API instance
*/
getAPI(version: 1): API;
}
export const enum GitErrorCodes {
BadConfigFile = 'BadConfigFile',
AuthenticationFailed = 'AuthenticationFailed',
NoUserNameConfigured = 'NoUserNameConfigured',
NoUserEmailConfigured = 'NoUserEmailConfigured',
NoRemoteRepositorySpecified = 'NoRemoteRepositorySpecified',
NotAGitRepository = 'NotAGitRepository',
NotAtRepositoryRoot = 'NotAtRepositoryRoot',
Conflict = 'Conflict',
StashConflict = 'StashConflict',
UnmergedChanges = 'UnmergedChanges',
PushRejected = 'PushRejected',
RemoteConnectionError = 'RemoteConnectionError',
DirtyWorkTree = 'DirtyWorkTree',
CantOpenResource = 'CantOpenResource',
GitNotFound = 'GitNotFound',
CantCreatePipe = 'CantCreatePipe',
CantAccessRemote = 'CantAccessRemote',
RepositoryNotFound = 'RepositoryNotFound',
RepositoryIsLocked = 'RepositoryIsLocked',
BranchNotFullyMerged = 'BranchNotFullyMerged',
NoRemoteReference = 'NoRemoteReference',
InvalidBranchName = 'InvalidBranchName',
BranchAlreadyExists = 'BranchAlreadyExists',
NoLocalChanges = 'NoLocalChanges',
NoStashFound = 'NoStashFound',
LocalChangesOverwritten = 'LocalChangesOverwritten',
NoUpstreamBranch = 'NoUpstreamBranch',
IsInSubmodule = 'IsInSubmodule',
WrongCase = 'WrongCase',
CantLockRef = 'CantLockRef',
CantRebaseMultipleBranches = 'CantRebaseMultipleBranches',
PatchDoesNotApply = 'PatchDoesNotApply',
NoPathFound = 'NoPathFound',
UnknownPath = 'UnknownPath',
}

21
tsconfig.json Normal file
View File

@ -0,0 +1,21 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"outDir": "out",
"lib": [
"es6"
],
"sourceMap": true,
"rootDir": "src",
"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. */
},
"exclude": [
"node_modules",
".vscode-test"
]
}

15
tslint.json Normal file
View File

@ -0,0 +1,15 @@
{
"rules": {
"no-string-throw": true,
"no-unused-expression": true,
"no-duplicate-variable": true,
"curly": true,
"class-name": true,
"semicolon": [
true,
"always"
],
"triple-equals": true
},
"defaultSeverity": "warning"
}

View File

@ -0,0 +1,42 @@
# Welcome to your VS Code Extension
## What's in the folder
* This folder contains all of the files necessary for your extension.
* `package.json` - this is the manifest file in which you declare your extension and command.
* The sample plugin registers a command and defines its title and command name. With this information VS Code can show the command in the command palette. It doesnt yet need to load the plugin.
* `src/extension.ts` - this is the main file where you will provide the implementation of your command.
* The file exports one function, `activate`, which is called the very first time your extension is activated (in this case by executing the command). Inside the `activate` function we call `registerCommand`.
* We pass the function containing the implementation of the command as the second parameter to `registerCommand`.
## Get up and running straight away
* Press `F5` to open a new window with your extension loaded.
* Run your command from the command palette by pressing (`Ctrl+Shift+P` or `Cmd+Shift+P` on Mac) and typing `Hello World`.
* Set breakpoints in your code inside `src/extension.ts` to debug your extension.
* Find output from your extension in the debug console.
## Make changes
* You can relaunch the extension from the debug toolbar after changing code in `src/extension.ts`.
* You can also reload (`Ctrl+R` or `Cmd+R` on Mac) the VS Code window with your extension to load your changes.
## Explore the API
* You can open the full set of our API when you open the file `node_modules/@types/vscode/index.d.ts`.
## Run tests
* Open the debug viewlet (`Ctrl+Shift+D` or `Cmd+Shift+D` on Mac) and from the launch configuration dropdown pick `Extension Tests`.
* Press `F5` to run the tests in a new window with your extension loaded.
* See the output of the test result in the debug console.
* Make changes to `src/test/suite/extension.test.ts` or create new test files inside the `test/suite` folder.
* The provided test runner will only consider files matching the name pattern `**.test.ts`.
* You can create folders inside the `test` folder to structure your tests any way you want.
## Go further
* Reduce the extension size and improve the startup time by [bundling your extension](https://code.visualstudio.com/api/working-with-extensions/bundling-extension).
* [Publish your extension](https://code.visualstudio.com/api/working-with-extensions/publishing-extension) on the VSCode extension marketplace.
* Automate builds by setting up [Continuous Integration](https://code.visualstudio.com/api/working-with-extensions/continuous-integration).