-
Notifications
You must be signed in to change notification settings - Fork 1
/
cargo-toml.ts
46 lines (38 loc) 路 1.5 KB
/
cargo-toml.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import elementReady from 'element-ready';
import toml from 'toml'
import fetchDom from '~/util/fetch-dom';
export const CARGO_TOML_FILE = 'Cargo.toml'
export const ERROR_MESSAGE = 'cratehub: there was an error while';
export function isCargoToml() {
// Example URLs:
// https://github.com/rust-lang/rust/blob/master/Cargo.toml
const pathnameParts = window.location.pathname.split('/');
return pathnameParts[3] === 'blob' && pathnameParts.pop() === CARGO_TOML_FILE;
}
export function hasCargoToml() {
return Boolean(getCargoTomlURL());
}
export function getCargoTomlURL() {
const packageLink = (document.querySelector(`#files ~ div [title="${CARGO_TOML_FILE}"]`) || document.querySelector(`.files [title="${CARGO_TOML_FILE}"]`)) as HTMLAnchorElement;
if (packageLink) {
return packageLink.href;
}
}
export function tomlToJson(tomlData: string) {
return toml.parse(tomlData);
}
// https://github.com/zellij-org/zellij/blob/bg-and-fg-color-ansi/Cargo.toml
export function getRepoBlobPath(link: string): string | undefined {
return (link.match(/.+blob\/.+\//) || [])[0];
}
export async function getCargoJson(isCargoToml: boolean, cargoTomlURL?: string) {
const codeDoc = isCargoToml ? document : cargoTomlURL ? await fetchDom(cargoTomlURL) : null;
if (codeDoc) {
const tomlBlobElement = await elementReady('.blob-wrapper table', {
target: <Document>codeDoc,
});
if (tomlBlobElement && tomlBlobElement.textContent) {
return tomlToJson(tomlBlobElement.textContent)
}
}
}