Skip to content

Commit

Permalink
WIP: move all deno scripts to .ts files, allow their discovery, prep …
Browse files Browse the repository at this point in the history
  • Loading branch information
balupton committed Sep 13, 2024
1 parent 6860035 commit d86e060
Show file tree
Hide file tree
Showing 5 changed files with 113 additions and 116 deletions.
66 changes: 3 additions & 63 deletions commands.beta/wallhaven-helper
Original file line number Diff line number Diff line change
Expand Up @@ -68,70 +68,10 @@ function wallhaven_helper() (
-- "${collections[@]}"
)"

# collection
local temp_deno_script
temp_deno_script="$(
fs-temp \
--directory='wallhaven-helper' \
--file='deno.ts'
)"
cat <<EOF >"$temp_deno_script"
const url = new URL(Deno.args[0])
function stderr(text: string) {
return Deno.stderr.write(
new TextEncoder().encode(text + "\n")
);
}
function stdout(text: string) {
return Deno.stdout.write(
new TextEncoder().encode(text + "\n")
);
}
function wait(ms: number, callback: () => void) {
return new Promise((resolve, reject) => {
setTimeout(function () {
try {
resolve(callback())
} catch (error) {
reject(error)
}
}, ms)
})
}
async function fetch_next_page() {
await stderr('Fetching: ' + url.toString())
const req = await fetch(url)
if ( req.status === 429 ) {
await stderr('Waiting 45 seconds for rate limiting.')
return await wait(45 * 1000, fetch_next_page)
}
const text = await req.text()
const json: any = await Promise.resolve().then(function () {
try {
return JSON.parse(text)
} catch (err) {
console.error('Failed to parse JSON:', err, text)
return Promise.reject('Failed to download ' + url)
}
})
const urls = json.data.map( (item: any) => item.path )
await stdout(urls.join('\n'))
if ( json.meta.last_page != json.meta.current_page ) {
url.searchParams.set('page', String(json.meta.current_page + 1))
fetch_next_page()
}
}
await fetch_next_page()
EOF

# run the deno script to fetch the wallpaper urls via the api and store them in a file
local temp_list_file
temp_list_file="$(
fs-temp \
--directory='wallhaven-helper' \
--file="$username-$collection.txt"
)"
deno run --allow-net --quiet "$temp_deno_script" "https://wallhaven.cc/api/v1/collections/$username/$collection?apikey=$apikey" | tee "$temp_list_file"
local deno_script
deno_script="$(command -v 'wallhaven-helper.ts')"
deno run --allow-net --quiet "$deno_script" "$apikey" "$username" "$collection" | tee "$temp_list_file"

# with that file, download each of them
local url
Expand Down
49 changes: 49 additions & 0 deletions commands.beta/wallhaven-helper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
// deno-lint-ignore-file no-explicit-any
const [apikey, username, collection] = Deno.args
if (!apikey || !username || !collection) {
throw new Error('Missing arguments: apikey, username, collection')
}
const url = new URL(
`https://wallhaven.cc/api/v1/collections/${username}/${collection}?apikey=${apikey}`,
)
function stderr(text: string) {
return Deno.stderr.write(new TextEncoder().encode(text + '\n'))
}
function stdout(text: string) {
return Deno.stdout.write(new TextEncoder().encode(text + '\n'))
}
function wait(ms: number, callback: () => void) {
return new Promise((resolve, reject) => {
setTimeout(function () {
try {
resolve(callback())
} catch (error) {
reject(error)
}
}, ms)
})
}
async function fetchNextPage() {
await stderr('Fetching: ' + url.toString())
const req = await fetch(url)
if (req.status === 429) {
await stderr('Waiting 45 seconds for rate limiting.')
return await wait(45 * 1000, fetchNextPage)
}
const text = await req.text()
const json: any = await Promise.resolve().then(function () {
try {
return JSON.parse(text)
} catch (err) {
console.error('Failed to parse JSON:', err, text)
return Promise.reject('Failed to download ' + url)
}
})
const urls = json.data.map((item: any) => item.path)
await stdout(urls.join('\n'))
if (json.meta.last_page !== json.meta.current_page) {
url.searchParams.set('page', String(json.meta.current_page + 1))
fetchNextPage()
}
}
await fetchNextPage()
54 changes: 4 additions & 50 deletions commands/brew-installed
Original file line number Diff line number Diff line change
Expand Up @@ -110,59 +110,13 @@ function brew_installed() (
function do_brew_advanced {
# handles --requested, --cask, and --formula

# ensure deno exists
# prep
setup-util-deno --quiet

# prepare as the .ts extension is essential
local temp_deno_script
temp_deno_script="$(fs-temp --directory='brew-installed' --file='deno.ts')"
cat <<-EOF >"$temp_deno_script"
// parse stdin
import { readLines } from "https://deno.land/std/io/bufio.ts";
let data = "";
for await (const line of readLines(Deno.stdin)) {
data += line;
}
const json = JSON.parse(data);
// prepare result
const names = new Set<string>();
// add casks if not filtered to only formula
if ( Deno.args.includes('--formula') === false ) {
// all casks are by request, so no need for special --requested handling for casks
for (const cask of json.casks.filter((i: any) => i.installed)) {
names.add(cask.full_token);
}
}
// add formulas if not filtered to only casks
if ( Deno.args.includes('--cask') === false ) {
if ( Deno.args.includes('--requested') ) {
// only requested formula
for (const formula of json.formulae) {
if (formula.installed.find((i: any) => i.installed_on_request)) {
names.add(formula.full_name);
}
}
} else {
// all formula
for (const formula of json.formulae.filter((i: any) => i.installed)) {
names.add(formula.full_name);
}
}
}
// output result
if (names.size) {
await Deno.stdout.write(
new TextEncoder().encode(Array.from(names).sort().concat("").join("\n"))
);
}
EOF

# run
"${brew_info_cmd[@]}" | deno run --quiet "$temp_deno_script" "${deno_script_args[@]}"
local deno_script
deno_script="$(command -v 'brew-installed.ts')"
"${brew_info_cmd[@]}" | deno run --quiet "$deno_script" "${deno_script_args[@]}"
}

# get names of requested packages
Expand Down
39 changes: 39 additions & 0 deletions commands/brew-installed.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// deno-lint-ignore-file no-explicit-any

// parse stdin
const json = await new Response(Deno.stdin.readable).json()

// prepare result
const names = new Set<string>()

// add casks if not filtered to only formula
if (Deno.args.includes('--formula') === false) {
// all casks are by request, so no need for special --requested handling for casks
for (const cask of json.casks.filter((i: any) => i.installed)) {
names.add(cask.full_token)
}
}

// add formulas if not filtered to only casks
if (Deno.args.includes('--cask') === false) {
if (Deno.args.includes('--requested')) {
// only requested formula
for (const formula of json.formulae) {
if (formula.installed.find((i: any) => i.installed_on_request)) {
names.add(formula.full_name)
}
}
} else {
// all formula
for (const formula of json.formulae.filter((i: any) => i.installed)) {
names.add(formula.full_name)
}
}
}

// output result
if (names.size) {
await Deno.stdout.write(
new TextEncoder().encode(Array.from(names).sort().concat('').join('\n')),
)
}
21 changes: 18 additions & 3 deletions commands/echo-regexp
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ function echo_regexp() (
}

# args
local item option_flags='' option_args=()
local item option_flags='' option_args=() option_inputs=()
while test "$#" -ne 0; do
item="$1"
shift
Expand Down Expand Up @@ -131,7 +131,7 @@ function echo_regexp() (
fi
;;
'--')
option_args+=("$@")
option_inputs+=("$@")
shift $#
break
;;
Expand All @@ -147,8 +147,23 @@ function echo_regexp() (
# =====================================
# Action

# prep
local deno_script
deno_script="$(command -v 'echo-regexp.ts')"
setup-util-deno --quiet
deno run --quiet "$DOROTHY/commands/echo-regexp.ts" "$option_flags" "${option_args[@]}"

function do_regexp {
deno run --quiet "$deno_script" "$option_flags" "${option_args[@]}"
}

if test "${#option_inputs[@]}" -eq 0; then
do_regexp
else
local input
for input in "${option_inputs[@]}"; do
__print_lines "$input" | do_regexp
done
fi
)

# fire if invoked standalone
Expand Down

0 comments on commit d86e060

Please sign in to comment.