Made it Prettier(tm)

This commit is contained in:
Juha Ristolainen 2017-11-08 21:03:53 +01:00
parent 2392b782b7
commit 01cd77e519
5 changed files with 276 additions and 242 deletions

View File

@ -1,78 +1,81 @@
import { Pulse } from "./pulse";
import { getISOTimestamp, getLanguageName } from "./utils";
import * as axios from "axios";
export class CodeStatsAPI {
private API_KEY = null;
private UPDATE_URL = "https://codestats.net/api/my/pulses";
private axios = null;
constructor(apiKey: string, apiURL: string) {
this.API_KEY = apiKey;
this.UPDATE_URL = apiURL;
if (this.API_KEY === null || this.API_KEY === undefined || this.API_KEY === '') {
return;
}
this.axios = axios.default.create({
baseURL: this.UPDATE_URL,
timeout: 10000,
headers: {
"X-API-Token": this.API_KEY,
"Content-Type": "application/json"
}
});
private API_KEY = null;
private UPDATE_URL = "https://codestats.net/api/my/pulses";
private axios = null;
constructor(apiKey: string, apiURL: string) {
this.API_KEY = apiKey;
this.UPDATE_URL = apiURL;
if (
this.API_KEY === null ||
this.API_KEY === undefined ||
this.API_KEY === ""
) {
return;
}
public sendUpdate(pulse: Pulse): axios.AxiosPromise {
// If we did not have API key, don't try to update
if (this.axios === null) {
return null;
}
this.axios = axios.default.create({
baseURL: this.UPDATE_URL,
timeout: 10000,
headers: {
"X-API-Token": this.API_KEY,
"Content-Type": "application/json"
}
});
}
// tslint:disable-next-line:typedef
const data = new ApiJSON(new Date());
for (let lang of pulse.xps.keys()) {
let languageName: string = getLanguageName(lang);
let xp: number = pulse.getXP(lang);
data.xps.push(new ApiXP(languageName, xp));
}
let json: string = JSON.stringify(data);
console.log(`JSON: ${json}`);
return this.axios.post(this.UPDATE_URL, json)
.then( (response) => {
console.log(response);
})
.then ( () => {
pulse.reset();
})
.catch((error) => {
console.log(error);
});
public sendUpdate(pulse: Pulse): axios.AxiosPromise {
// If we did not have API key, don't try to update
if (this.axios === null) {
return null;
}
// tslint:disable-next-line:typedef
const data = new ApiJSON(new Date());
for (let lang of pulse.xps.keys()) {
let languageName: string = getLanguageName(lang);
let xp: number = pulse.getXP(lang);
data.xps.push(new ApiXP(languageName, xp));
}
let json: string = JSON.stringify(data);
console.log(`JSON: ${json}`);
return this.axios
.post(this.UPDATE_URL, json)
.then(response => {
console.log(response);
})
.then(() => {
pulse.reset();
})
.catch(error => {
console.log(error);
});
}
}
class ApiJSON {
constructor(date: Date) {
this.coded_at = getISOTimestamp(new Date());
this.xps = new Array<ApiXP>();
}
constructor(date: Date) {
this.coded_at = getISOTimestamp(new Date());
this.xps = new Array<ApiXP>();
}
coded_at: string;
xps: Array<ApiXP>;
coded_at: string;
xps: Array<ApiXP>;
}
class ApiXP {
constructor(language: string, xp: number) {
this.language = language;
this.xp = xp;
}
constructor(language: string, xp: number) {
this.language = language;
this.xp = xp;
}
language: string;
xp: number;
language: string;
xp: number;
}

View File

@ -3,10 +3,9 @@ import { ExtensionContext } from "vscode";
import { XpCounter } from "./xp-counter";
export function activate(context: ExtensionContext): void {
let controller: XpCounter = new XpCounter();
context.subscriptions.push(controller);
let controller: XpCounter = new XpCounter();
context.subscriptions.push(controller);
}
// this method is called when your extension is deactivated
export function deactivate(): void {
}
export function deactivate(): void {}

View File

@ -1,33 +1,33 @@
export class Pulse {
xps: Map < string, number > ;
xps: Map<string, number>;
constructor() {
this.xps = new Map < string, number > ();
constructor() {
this.xps = new Map<string, number>();
}
public getXP(language: string): number {
let xp: number = this.xps.get(language);
if (xp === null || xp === undefined) {
return 0;
} else {
return xp;
}
}
public getXP(language: string): number {
let xp: number = this.xps.get(language);
public addXP(language: string, amount: number): void {
let xp: number = this.getXP(language);
if (xp === null || xp === undefined) {
return 0;
} else {
return xp;
}
}
xp += amount;
public addXP(language: string, amount: number): void {
let xp: number = this.getXP(language);
this.xps.set(language, xp);
}
xp += amount;
public get getXPs(): Map<string, number> {
return this.xps;
}
this.xps.set(language, xp);
}
public get getXPs(): Map < string, number > {
return this.xps;
}
public reset(): void {
this.xps = new Map < string, number > ();
}
public reset(): void {
this.xps = new Map<string, number>();
}
}

View File

@ -1,87 +1,95 @@
// converted to ts from https://github.com/Nicd/code-stats-atom/blob/master/lib/utils.js
export function getISOTimestamp(date: Date): string {
const offset: number = -date.getTimezoneOffset();
const prefix: string = (offset >= 0) ? "+" : "-";
const offset: number = -date.getTimezoneOffset();
const prefix: string = offset >= 0 ? "+" : "-";
function pad(num: number): string {
const norm: number = Math.abs(Math.floor(num));
function pad(num: number): string {
const norm: number = Math.abs(Math.floor(num));
return ((norm < 10) ? "0" : "") + norm;
}
return (norm < 10 ? "0" : "") + norm;
}
return date.getFullYear() +
"-" + pad(date.getMonth() + 1) +
"-" + pad(date.getDate()) +
"T" + pad(date.getHours()) +
":" + pad(date.getMinutes()) +
":" + pad(date.getSeconds()) +
prefix + pad(offset / 60) +
pad(offset % 60);
return (
date.getFullYear() +
"-" +
pad(date.getMonth() + 1) +
"-" +
pad(date.getDate()) +
"T" +
pad(date.getHours()) +
":" +
pad(date.getMinutes()) +
":" +
pad(date.getSeconds()) +
prefix +
pad(offset / 60) +
pad(offset % 60)
);
}
export function getLanguageName(langId: string): string {
// currently supported language ids in vscode as of 2017-03-18
let languageNames: { [key:string]: string; } = {
"plaintext": "Plain text",
"Log": "Log",
"bat": "Batch",
"clojure": "Clojure",
"coffeescript": "CoffeeScript",
"c": "C",
"cpp": "C++",
"csharp": "C#",
"css": "CSS",
"diff": "Diff",
"dockerfile": "Docker",
"elixir": "Elixir",
"elm": "Elm",
"fsharpcss": "F#",
"git-commit": "Git",
"git-rebase": "Git",
"go": "Go",
"groovy": "Groovy",
"handlebars": "Handlebars",
"hlsl": "HLSL",
"html": "HTML",
"ini": "Ini",
"properties": "Properties",
"java": "Java",
"javascriptreact": "JavaScript (React)",
"javascript": "JavaScript",
"jsx-tags": "JavaScript (JSX)",
"json": "JSON",
"less": "LESS",
"lua": "Lua",
"makefile": "Makefile",
"markdown": "Markdown",
"objective-c": "Objective-C",
"perl": "Perl",
"perl6": "Perl 6",
"php": "PHP",
"powershell": "PowerShell",
"jade": "Pug",
"python": "Python",
"r": "R",
"razor": "Razor",
"ruby": "Ruby",
"rust": "Rust",
"scss": "SCSS",
"shaderlab": "Shaderlab",
"shellscript": "Shell Script",
"sql": "SQL",
"swift": "Swift",
"typescript": "TypeScript",
"typescriptreact": "TypeScript (React)",
"vb": "Visual Basic",
"xml": "XML",
"xsl": "XSL",
"yaml": "YAML"
};
// currently supported language ids in vscode as of 2017-03-18
let languageNames: { [key: string]: string } = {
plaintext: "Plain text",
Log: "Log",
bat: "Batch",
clojure: "Clojure",
coffeescript: "CoffeeScript",
c: "C",
cpp: "C++",
csharp: "C#",
css: "CSS",
diff: "Diff",
dockerfile: "Docker",
elixir: "Elixir",
elm: "Elm",
fsharpcss: "F#",
"git-commit": "Git",
"git-rebase": "Git",
go: "Go",
groovy: "Groovy",
handlebars: "Handlebars",
hlsl: "HLSL",
html: "HTML",
ini: "Ini",
properties: "Properties",
java: "Java",
javascriptreact: "JavaScript (React)",
javascript: "JavaScript",
"jsx-tags": "JavaScript (JSX)",
json: "JSON",
less: "LESS",
lua: "Lua",
makefile: "Makefile",
markdown: "Markdown",
"objective-c": "Objective-C",
perl: "Perl",
perl6: "Perl 6",
php: "PHP",
powershell: "PowerShell",
jade: "Pug",
python: "Python",
r: "R",
razor: "Razor",
ruby: "Ruby",
rust: "Rust",
scss: "SCSS",
shaderlab: "Shaderlab",
shellscript: "Shell Script",
sql: "SQL",
swift: "Swift",
typescript: "TypeScript",
typescriptreact: "TypeScript (React)",
vb: "Visual Basic",
xml: "XML",
xsl: "XSL",
yaml: "YAML"
};
let languageName: string = languageNames[langId];
let languageName: string = languageNames[langId];
if (languageName === null || languageName === undefined) {
return langId;
}
return languageName;
if (languageName === null || languageName === undefined) {
return langId;
}
return languageName;
}

View File

@ -1,24 +1,34 @@
// tslint:disable-next-line:max-line-length
import { Disposable, workspace, window, StatusBarItem, TextDocument, StatusBarAlignment, TextDocumentChangeEvent, Range, WorkspaceConfiguration } from "vscode";
import {
Disposable,
workspace,
window,
StatusBarItem,
TextDocument,
StatusBarAlignment,
TextDocumentChangeEvent,
Range,
WorkspaceConfiguration
} from "vscode";
import { Pulse } from "./pulse";
import { CodeStatsAPI } from "./code-stats-api";
export class XpCounter {
private combinedDisposable: Disposable;
private statusBarItem: StatusBarItem;
private pulse: Pulse;
private api: CodeStatsAPI;
private updateTimeout: any;
private combinedDisposable: Disposable;
private statusBarItem: StatusBarItem;
private pulse: Pulse;
private api: CodeStatsAPI;
private updateTimeout: any;
// private languages: Array<string> = ["typescript", "javascript"];
// private languages: Array<string> = ["typescript", "javascript"];
// wait 10s after each change in the document before sending an update
private UPDATE_DELAY = 10000;
// wait 10s after each change in the document before sending an update
private UPDATE_DELAY = 10000;
constructor() {
this.pulse = new Pulse();
constructor() {
this.pulse = new Pulse();
/* // print out supported language names
/* // print out supported language names
let allLanguages = languages.getLanguages().then(
(result => {
console.log(JSON.stringify(result));
@ -26,77 +36,91 @@ export class XpCounter {
);
*/
this.initAPI();
this.initAPI();
if (!this.statusBarItem) {
this.statusBarItem = window.createStatusBarItem(StatusBarAlignment.Left);
}
let subscriptions: Disposable[] = [];
workspace.onDidChangeTextDocument(this.onTextDocumentChanged, this, subscriptions);
workspace.onDidChangeConfiguration(this.initAPI, this, subscriptions);
this.combinedDisposable = Disposable.from(...subscriptions);
if (!this.statusBarItem) {
this.statusBarItem = window.createStatusBarItem(StatusBarAlignment.Left);
}
dispose(): void {
this.combinedDisposable.dispose();
this.statusBarItem.dispose();
let subscriptions: Disposable[] = [];
workspace.onDidChangeTextDocument(
this.onTextDocumentChanged,
this,
subscriptions
);
workspace.onDidChangeConfiguration(this.initAPI, this, subscriptions);
this.combinedDisposable = Disposable.from(...subscriptions);
}
dispose(): void {
this.combinedDisposable.dispose();
this.statusBarItem.dispose();
}
private onTextDocumentChanged(event: TextDocumentChangeEvent): void {
this.updateXpCount(event.document, 1);
}
public updateXpCount(document: TextDocument, changeCount: number): void {
let show: boolean;
if (this.isSupportedLanguage(document.languageId)) {
this.pulse.addXP(document.languageId, changeCount);
show = true;
} else {
show = false;
}
this.updateStatusBar(show, `${this.pulse.getXP(document.languageId)}`);
// each change resets the timeout so we only send updates when there is a 10s delay in updates to the document
if (this.updateTimeout !== null) {
clearTimeout(this.updateTimeout);
}
private onTextDocumentChanged(event: TextDocumentChangeEvent): void {
this.updateXpCount(event.document, 1);
this.updateTimeout = setTimeout(() => {
const promise = this.api.sendUpdate(this.pulse);
if (promise !== null) {
promise.then(() => {
this.updateStatusBar(
show,
`${this.pulse.getXP(document.languageId)}`
);
});
}
}, this.UPDATE_DELAY);
}
private updateStatusBar(show: boolean, changeCount: string): void {
if (!show) {
this.statusBarItem.hide();
} else {
this.statusBarItem.text = `$(pencil) C::S ${changeCount}`;
this.statusBarItem.show();
}
}
private isSupportedLanguage(language: string): boolean {
// todo: check supported languages
// only update xp if one of supported languages
return true;
}
private initAPI() {
let config: WorkspaceConfiguration = workspace.getConfiguration(
"codestats"
);
if (!config) {
return;
}
public updateXpCount(document: TextDocument, changeCount: number): void {
let show: boolean;
if (this.isSupportedLanguage(document.languageId)) {
this.pulse.addXP(document.languageId, changeCount);
show = true;
} else {
show = false;
}
this.updateStatusBar(show, `${this.pulse.getXP(document.languageId)}`);
// each change resets the timeout so we only send updates when there is a 10s delay in updates to the document
if (this.updateTimeout !== null) {
clearTimeout(this.updateTimeout);
}
this.updateTimeout = setTimeout(() => {
const promise = this.api.sendUpdate(this.pulse);
if (promise !== null) {
promise.then(() => {
this.updateStatusBar(show, `${this.pulse.getXP(document.languageId)}`);
});
}
}, this.UPDATE_DELAY);
}
private updateStatusBar(show: boolean, changeCount: string): void {
if (!show) {
this.statusBarItem.hide();
} else {
this.statusBarItem.text = `$(pencil) C::S ${changeCount}`;
this.statusBarItem.show();
}
}
private isSupportedLanguage(language: string): boolean {
// todo: check supported languages
// only update xp if one of supported languages
return true;
}
private initAPI() {
let config: WorkspaceConfiguration = workspace.getConfiguration("codestats");
if (!config) {
return;
}
const apiKey: string = config.get("apikey");
const apiURL: string = config.get("apiurl");
console.log("code-stats-vscode setting up with API URL", apiURL, "and key", apiKey);
this.api = new CodeStatsAPI(apiKey, apiURL);
}
const apiKey: string = config.get("apikey");
const apiURL: string = config.get("apiurl");
console.log(
"code-stats-vscode setting up with API URL",
apiURL,
"and key",
apiKey
);
this.api = new CodeStatsAPI(apiKey, apiURL);
}
}