copykitku/src/utils.ts
2021-02-26 00:57:21 +01:00

109 lines
3 KiB
TypeScript

/*
* Copykitku. Copyright (C) 2020 selfisekai <laura@selfisekai.rocks> and other contributors.
*
* This is free software, and you are welcome to redistribute it
* under the GNU General Public License 3.0 or later; see the LICENSE file for details,
* or, if the file is unavailable, visit <https://www.gnu.org/licenses/gpl-3.0-standalone.html>.
*/
import { readFileSync, writeFileSync } from 'fs-extra';
import toml from '@iarna/toml';
import appdataPath from 'appdata-path';
import path from 'path';
import { CopykitkuConfig, CopykitkuProjectConfig, ENTITY_TYPE } from './types';
export const DEFAULT_CONFIG: CopykitkuConfig = {
vendorConfigs: [],
};
export const getConfigPath = () => appdataPath('copykitku.toml');
export const getConfig = () => {
try {
const file = readFileSync(getConfigPath());
return (toml.parse(file.toString('utf-8')) as unknown) as CopykitkuConfig;
} catch (err) {
if (err.code === 'ENOENT') {
setConfig(DEFAULT_CONFIG);
}
return DEFAULT_CONFIG;
}
};
export const setConfig = (config: CopykitkuConfig) =>
writeFileSync(getConfigPath(), toml.stringify({ ...DEFAULT_CONFIG, ...config } as any), {
encoding: 'utf-8',
});
export const getProjectConfigPath = () => path.join(process.cwd(), '.copykitkurc.toml');
export const getProjectConfig = () => {
try {
const file = readFileSync(getProjectConfigPath());
return (toml.parse(file.toString('utf-8')) as unknown) as CopykitkuProjectConfig;
} catch (err) {
if (err.code === 'ENOENT') {
return {};
} else {
// project config file exists, but cannot be accessed/parsed for some reason
throw err;
}
}
};
export type Path =
| {
domain: string;
path: string;
entity: ENTITY_TYPE;
entityID: string;
}
| {
domain: string;
path: string;
entity: null;
entityID: null;
};
export const parsePath = (path: string): Path => {
let mobj = /^https?:\/\/([^/]+)\/([a-zA-Z\d-]+\/(?:[a-zA-Z\d-]+\/)*?[a-zA-Z\d-]+)(?:\/-)?(?:\/(issues|pulls?|merge_requests)(?:\/(\d+))?\/?)(?:\?[^#]+)?(?:#.+)?$/.exec(
path,
);
if (mobj) {
return {
domain: mobj[1],
path: mobj[2],
entity: {
issues: ENTITY_TYPE.ISSUE,
merge_requests: ENTITY_TYPE.MERGE_REQUEST,
pull: ENTITY_TYPE.MERGE_REQUEST,
pulls: ENTITY_TYPE.MERGE_REQUEST,
}[mobj[3] as 'issues' | 'merge_requests' | 'pull' | 'pulls'],
entityID: mobj[4],
};
}
mobj = /^https?:\/\/([^/]+)\/([a-zA-Z\d-]+\/(?:[a-zA-Z\d-]+\/)*?[a-zA-Z\d-]+)(?:\/-)?(?:\/commit(?:\/([a-f\d]+))(?:\.(patch|diff))?\/?)(?:\?[^#]+)?(?:#.+)?$/.exec(
path,
);
if (mobj) {
return {
domain: mobj[1],
path: mobj[2],
entity: ENTITY_TYPE.COMMIT,
entityID: mobj[3],
};
}
mobj = /^https?:\/\/([^/]+)\/([a-zA-Z\d-]+\/(?:[a-zA-Z\d-]+\/)*?[a-zA-Z\d-]+)\/?(?:\?[^#]+)?(?:#.+)?$/.exec(
path,
);
if (mobj) {
return {
domain: mobj[1],
path: mobj[2],
entity: null,
entityID: null,
};
}
throw new Error('Path could not be parsed');
};