Skip to content

Commit

Permalink
✨ Fix not support other than latest ver
Browse files Browse the repository at this point in the history
  • Loading branch information
ChenCMD committed Nov 15, 2020
1 parent 66b3f4f commit ad5010e
Show file tree
Hide file tree
Showing 12 changed files with 171 additions and 35 deletions.
5 changes: 5 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,11 @@
"markdownDescription": "%mcdutil.config.scoreOperation.valueScale%",
"default": 1
},
"mcdutil.createDatapackTemplate.dataVersion": {
"type": "string",
"markdownDescription": "%mcdutil.config.createDatapackTemplate.dataVersion%",
"default": "Latest release"
},
"mcdutil.createDatapackTemplate.customTemplate": {
"type": "array",
"items": {
Expand Down
1 change: 1 addition & 0 deletions package.nls.ja.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,5 +33,6 @@
"mcdutil.config.createDatapackTemplate.customTemplate.generates.relativeFilePath": "DatapackName以下の相対ファイルパス (ファイルの場合拡張子まで記載が必要です)",
"mcdutil.config.createDatapackTemplate.customTemplate.generates.relativeFilePath.error": "\\\\ : * ? \" < > | はファイル/フォルダ名に使えません",
"mcdutil.config.createDatapackTemplate.customTemplate.generates.content": "ファイルの内容 (基本的に一つのアイテムは1行として解釈されます)",
"mcdutil.config.createDatapackTemplate.dataVersion": "使用するバニラデータのバージョン",
"mcdutil.config.createFile.fileTemplate": "**データパックファイルを作成する**: ファイルの生成時に記載されている内容 (ファイル種毎に設定が可能です)"
}
1 change: 1 addition & 0 deletions package.nls.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,5 +33,6 @@
"mcdutil.config.createDatapackTemplate.customTemplate.generates.relativeFilePath": "Relative file path under DatapackName (In case of file, extension is required)",
"mcdutil.config.createDatapackTemplate.customTemplate.generates.relativeFilePath.error": "\\\\ : * ? \" < > | cannot be used for file/folder names",
"mcdutil.config.createDatapackTemplate.customTemplate.generates.content": "File contents (Basically one item is interpreted as one line)",
"mcdutil.config.createDatapackTemplate.dataVersion": "Version of vanilla data to use",
"mcdutil.config.createFile.fileTemplate": "**Create Datapack file**: Contents described when the file is generated (can be set for each file type)"
}
23 changes: 15 additions & 8 deletions src/commands/createDatapackTemplate/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,10 @@ import { locale } from '../../locales';
import { createMessageItemsHasId } from './types/MessageItems';
import { resolveVars, VariableContainer } from '../../types/VariableContainer';
import { getFileType } from '../../types/FileTypes';
import { codeConsole, config } from '../../extension';
import { codeConsole, config, versionInformation } from '../../extension';
import rfdc from 'rfdc';
import { getGitHubData } from '../../utils/downloader';
import { GenerateFileData } from './types/QuickPickFiles';
import { getVanillaData } from '../../utils/vanillaData';

export async function createDatapack(): Promise<void> {
// フォルダ選択
Expand Down Expand Up @@ -109,18 +110,24 @@ async function create(dir: Uri): Promise<void> {
createItemData.push(rfdc()(packMcMetaData));

try {
for (const func of funcs.map((v, i) => ({ index: i + 1, value: v }))) {
for (const func of funcs.map((value, index) => ({ value, index }))) {
await window.withProgress({
location: ProgressLocation.Notification,
cancellable: false,
title: locale('create-datapack-template.progress.title')
}, async progress => {
progress.report({ increment: 0, message: locale('create-datapack-template.progress.download', func.index, funcs.length) });

const data = await getGitHubData(func.value, (_, m) =>
progress.report({ increment: 100 / m, message: locale('create-datapack-template.progress.download', func.index, funcs.length) })
const message = locale('create-datapack-template.progress.download', func.index + 1, funcs.length);
progress.report({ increment: 0, message });

const datas = await getVanillaData(
config.createDatapackTemplate.dataVersion,
versionInformation,
func.value,
func.value.rel,
(_, m) => progress.report({ increment: 100 / m, message })
);
createItemData.push(...data);
for (const data of datas)
createItemData.push({ type: 'file', ...data } as GenerateFileData);
});
}
} catch (error) {
Expand Down
9 changes: 3 additions & 6 deletions src/commands/createDatapackTemplate/types/QuickPickFiles.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { QuickPickItem } from 'vscode';
import { ReposGetContentResponseData } from '@octokit/types/dist-types/generated/Endpoints';
import { FileData } from '../../../types/FileData';
import { AskGitHubData } from '../../../types/AskGitHubData';

export interface QuickPickFiles extends QuickPickItem {
generates: GenerateFileData[],
Expand All @@ -11,10 +12,6 @@ export interface GenerateFileData extends FileData {
type: 'file' | 'folder'
}

export interface GetGitHubDataFunc {
owner: string,
repo: string,
ref: string,
path: string,
relativeFilePath: (data: ReposGetContentResponseData) => string
export interface GetGitHubDataFunc extends AskGitHubData {
rel: (data: ReposGetContentResponseData) => string
}
8 changes: 4 additions & 4 deletions src/commands/createDatapackTemplate/utils/data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ export const pickItems: QuickPickFiles[] = [
repo: 'vanilla-datapack',
ref: '%version%-data',
path: 'data/minecraft/tags/blocks',
relativeFilePath: (data: ReposGetContentResponseData): string => data.path
rel: (data: ReposGetContentResponseData): string => data.path
}
]
},
Expand All @@ -81,7 +81,7 @@ export const pickItems: QuickPickFiles[] = [
repo: 'vanilla-datapack',
ref: '%version%-data',
path: 'data/minecraft/tags/entity_types',
relativeFilePath: (data: ReposGetContentResponseData): string => data.path
rel: (data: ReposGetContentResponseData): string => data.path
}
]
},
Expand All @@ -94,7 +94,7 @@ export const pickItems: QuickPickFiles[] = [
repo: 'vanilla-datapack',
ref: '%version%-data',
path: 'data/minecraft/tags/fluids',
relativeFilePath: (data: ReposGetContentResponseData): string => data.path
rel: (data: ReposGetContentResponseData): string => data.path
}
]
},
Expand All @@ -107,7 +107,7 @@ export const pickItems: QuickPickFiles[] = [
repo: 'vanilla-datapack',
ref: '%version%-data',
path: 'data/minecraft/tags/items',
relativeFilePath: (data: ReposGetContentResponseData): string => data.path
rel: (data: ReposGetContentResponseData): string => data.path
}
]
},
Expand Down
6 changes: 6 additions & 0 deletions src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,21 @@ import { ExtensionContext, commands, window, workspace, ConfigurationChangeEvent
import { copyResourcePath, createDatapack, createFile, scoreOperation } from './commands';
import { loadLocale } from './locales';
import { constructConfig } from './types/Config';
import { VersionInformation } from './types/VersionInformation';
import { getLatestVersions } from './utils/vanillaData';

export const codeConsole = window.createOutputChannel('MC Commander Util');
export let config = constructConfig(workspace.getConfiguration('mcdutil'));
export let versionInformation: VersionInformation | undefined;
const vscodeLanguage = getVSCodeLanguage();

/**
* @param {vscode.ExtensionContext} context
*/
export function activate(context: ExtensionContext): void {

getLatestVersions().then(info => versionInformation = info);

loadLocale(config.language, vscodeLanguage);

const disposable = [];
Expand Down
6 changes: 6 additions & 0 deletions src/types/AskGitHubData.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export interface AskGitHubData {
owner: string
repo: string
ref: string
path: string
}
2 changes: 2 additions & 0 deletions src/types/Config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ export interface Config {
valueScale: number
},
createDatapackTemplate: {
dataVersion: string
customTemplate: QuickPickFiles[]
},
createFile: {
Expand All @@ -36,6 +37,7 @@ export const defaultConfig: Config = {
valueScale: 1
},
createDatapackTemplate: {
dataVersion: 'Latest release',
customTemplate: []
},
createFile: {
Expand Down
35 changes: 35 additions & 0 deletions src/types/VersionInformation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/**
* @license
* MIT License
*
* Copyright (c) 2019-2020 SPGoding
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
export interface VersionInformation {
latestSnapshot: string,
latestRelease: string,
processedVersions: string[]
}

export const dummyVersionInformation: VersionInformation = {
latestRelease: '',
latestSnapshot: '',
processedVersions: []
};
20 changes: 3 additions & 17 deletions src/utils/downloader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { Octokit } from '@octokit/rest';
import { ReposGetContentResponseData } from '@octokit/types/dist-types/generated/Endpoints';
import { OctokitResponse } from '@octokit/types/dist-types/OctokitResponse';
import { setTimeOut } from './common';
import { GenerateFileData, GetGitHubDataFunc } from '../commands/createDatapackTemplate/types/QuickPickFiles';
import { AskGitHubData } from '../types/AskGitHubData';

export async function download(uri: string): Promise<string> {
return await new Promise((resolve, reject) => {
Expand All @@ -20,7 +20,7 @@ export async function download(uri: string): Promise<string> {
});
}

export async function getGitHubData(data: GetGitHubDataFunc, elementFunc: (index: number, max: number) => void): Promise<GenerateFileData[]> {
export async function getGitHubData(data: AskGitHubData): Promise<ReposGetContentResponseData[]> {
const octokit = new Octokit();
const files = await Promise.race([
octokit.repos.getContent({
Expand All @@ -31,19 +31,5 @@ export async function getGitHubData(data: GetGitHubDataFunc, elementFunc: (index
}) as unknown as OctokitResponse<ReposGetContentResponseData[]>,
setTimeOut<OctokitResponse<ReposGetContentResponseData[]>>(7000)
]);
// コンパイラが雑魚
const result: GenerateFileData[] = [];
for (const file of files.data.map((v, i) => ({ index: i, value: v }))) {
const content = await Promise.race([
download(file.value.download_url),
setTimeOut<string>(7000)
]);
result.push({
type: 'file',
relativeFilePath: data.relativeFilePath(file.value),
content: content.split('\n')
});
elementFunc(file.index, files.data.length);
}
return result;
return files.data;
}
90 changes: 90 additions & 0 deletions src/utils/vanillaData.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
/**
* @license
* MIT License
*
* Copyright (c) 2019-2020 SPGoding
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

import { ReposGetContentResponseData } from '@octokit/types/dist-types/generated/Endpoints';
import { codeConsole } from '../extension';
import { AskGitHubData } from '../types/AskGitHubData';
import { FileData } from '../types/FileData';
import { VersionInformation } from '../types/VersionInformation';
import { setTimeOut } from './common';
import { download, getGitHubData } from './downloader';

export async function getVanillaData(
versionOrLiteral: string,
versionInfo: VersionInformation | undefined,
askGitHubdata: AskGitHubData,
relProcessingFunc: (data: ReposGetContentResponseData) => string,
elementFunc: (index: number, max: number) => void
): Promise<FileData[]> {
askGitHubdata.ref = askGitHubdata.ref.replace(/%version%/, resolveVersion(versionOrLiteral, versionInfo));

const files = await getGitHubData(askGitHubdata);
const ans: FileData[] = [];

for (const file of files.map((value, index) => ({ index, value }))) {
const content = await Promise.race([
download(file.value.download_url),
setTimeOut<string>(7000)
]);
ans.push({
rel: relProcessingFunc(file.value),
content: content.split('\n')
});
elementFunc(file.index, files.length);
}
return ans;
}

function resolveVersion(versionOrLiteral: string, versionInformation: VersionInformation | undefined) {
if (!versionInformation)
return '1.16.4';
switch (versionOrLiteral.toLowerCase()) {
case 'latest snapshot':
return versionInformation.latestSnapshot;
case 'latest release':
return versionInformation.latestRelease;
default:
return versionOrLiteral;
}
}

export async function getLatestVersions(): Promise<VersionInformation | undefined> {
let ans: VersionInformation | undefined;
try {
codeConsole.appendLine('[LatestVersions] Fetching the latest versions...');
const str = await Promise.race([
download('https://launchermeta.mojang.com/mc/game/version_manifest.json'),
setTimeOut<string>(7000)
]);
const { latest: { release, snapshot }, versions }: { latest: { release: string, snapshot: string }, versions: { id: string }[] } = JSON.parse(str);
const processedVersion = '1.16.2';
const processedVersionIndex = versions.findIndex(v => v.id === processedVersion);
const processedVersions = processedVersionIndex >= 0 ? versions.slice(0, processedVersionIndex + 1).map(v => v.id) : [];
ans = (release && snapshot) ? { latestRelease: release, latestSnapshot: snapshot, processedVersions } : undefined;
} catch (e) {
codeConsole.appendLine(`[LatestVersions] ${e}`);
}
return ans;
}

0 comments on commit ad5010e

Please sign in to comment.