Merge branch 'trunk' of https://github.com/bugabinga/dotfiles into trunk
2a02f88cfdd57f93a8075aa90f9c0df1f63e6099
Oliver Krylow <o.krylow@isp-insoft.de> ·
unsigned
- Parent 1: 065723132b3d · Diff against parent 1
- Parent 2: a2df4842e1cc · Showing diff
bugabingas dorkfiles
2a02f88cfdd57f93a8075aa90f9c0df1f63e6099
Oliver Krylow <o.krylow@isp-insoft.de> ·
unsigned
+1279 / −1367 text lines
+5 / −1 text lines
+0 / −339 text lines
module completions { def "nu-complete pueue color" [] { [ "auto" "never" "always" ] } # Interact with the Pueue daemon export extern pueue [ --verbose(-v) # Verbose mode (-v, -vv, -vvv) --color: string@"nu-complete pueue color" # Colorize the output; auto enables color output when connected to a tty --config(-c): string # If provided, Pueue only uses this config file. This path can also be set via the "PUEUE_CONFIG_PATH" environment variable. The commandline option overwrites the environment variable! --profile(-p): string # The name of the profile that should be loaded from your config file --help(-h) # Print help --version(-V) # Print version ] # Enqueue a task for execution. There're many different options when scheduling a task. Check the individual option help texts for more information. Furthermore, please remember that scheduled commands are executed via your system shell. This means that the command needs proper shell escaping. The safest way to preserve shell escaping is to surround your command with quotes, for example: pueue add 'ls $HOME && echo "Some string"' export extern "pueue add" [ ...command: string # The command to be added --working-directory(-w): string # Specify current working directory --escape(-e) # Escape any special shell characters (" ", "&", "!", etc.). Beware: This implicitly disables nearly all shell specific syntax ("&&", "&>") --immediate(-i) # Immediately start the task --stashed(-s) # Create the task in Stashed state. Useful to avoid immediate execution if the queue is empty --delay(-d): string # Prevents the task from being enqueued until 'delay' elapses. See "enqueue" for accepted formats --group(-g): string # Assign the task to a group. Groups kind of act as separate queues. I.e. all groups run in parallel and you can specify the amount of parallel tasks for each group. If no group is specified, the default group will be used --after(-a): string # Start the task once all specified tasks have successfully finished. As soon as one of the dependencies fails, this task will fail as well --priority(-o): string # Start this task with a higher priority. The higher the number, the faster it will be processed --label(-l): string # Add some information for yourself. This string will be shown in the "status" table. There's no additional logic connected to it --print-task-id(-p) # Only return the task id instead of a text. This is useful when working with dependencies --help(-h) # Print help ] # Remove tasks from the list. Running or paused tasks need to be killed first export extern "pueue remove" [ ...task_ids: string # The task ids to be removed --help(-h) # Print help ] # Switches the queue position of two commands. Only works on queued and stashed commands export extern "pueue switch" [ task_id_1: string # The first task id task_id_2: string # The second task id --help(-h) # Print help ] # Stashed tasks won't be automatically started. You have to enqueue them or start them by hand export extern "pueue stash" [ ...task_ids: string # Stash these specific tasks --help(-h) # Print help ] # Enqueue stashed tasks. They'll be handled normally afterwards export extern "pueue enqueue" [ ...task_ids: string # Enqueue these specific tasks --delay(-d): string # Delay enqueuing these tasks until 'delay' elapses. See DELAY FORMAT below --help(-h) # Print help ] # Resume operation of specific tasks or groups of tasks. By default, this resumes the default group and all its tasks. Can also be used force-start specific tasks. export extern "pueue start" [ ...task_ids: string # Start these specific tasks. Paused tasks will resumed. Queued or Stashed tasks will be force-started --group(-g): string # Resume a specific group and all paused tasks in it. The group will be set to running and its paused tasks will be resumed --all(-a) # Resume all groups! All groups will be set to running and paused tasks will be resumed --children(-c) # Deprecated: this switch no longer has any effect --help(-h) # Print help ] # Restart failed or successful task(s). By default, identical tasks will be created and enqueued, but it's possible to restart in-place. You can also edit a few properties, such as the path and the command, before restarting. export extern "pueue restart" [ ...task_ids: string # Restart these specific tasks --all-failed(-a) # Restart all failed tasks across all groups. Nice to use in combination with `-i/--in-place` --failed-in-group(-g): string # Like `--all-failed`, but only restart tasks failed tasks of a specific group. The group will be set to running and its paused tasks will be resumed --start-immediately(-k) # Immediately start the tasks, no matter how many open slots there are. This will ignore any dependencies tasks may have --stashed(-s) # Set the restarted task to a "Stashed" state. Useful to avoid immediate execution --in-place(-i) # Restart the task by reusing the already existing tasks. This will overwrite any previous logs of the restarted tasks --not-in-place # Restart the task by creating a new identical tasks. Only applies, if you have the restart_in_place configuration set to true --edit(-e) # Edit the tasks' commands before restarting --edit-path(-p) # Edit the tasks' paths before restarting --edit-label(-l) # Edit the tasks' labels before restarting --edit-priority(-o) # Edit the tasks' priorities before restarting --help(-h) # Print help ] # Either pause running tasks or specific groups of tasks. By default, pauses the default group and all its tasks. A paused queue (group) won't start any new tasks. export extern "pueue pause" [ ...task_ids: string # Pause these specific tasks. Does not affect the default group, groups or any other tasks --group(-g): string # Pause a specific group --all(-a) # Pause all groups! --wait(-w) # Only pause the specified group and let already running tasks finish by themselves --children(-c) # Deprecated: this switch no longer has any effect --help(-h) # Print help ] # Kill specific running tasks or whole task groups.. Kills all tasks of the default group when no ids or a specific group are provided. export extern "pueue kill" [ ...task_ids: string # Kill these specific tasks --group(-g): string # Kill all running tasks in a group. This also pauses the group --all(-a) # Kill all running tasks across ALL groups. This also pauses all groups --children(-c) # Deprecated: this switch no longer has any effect --signal(-s): string # Send a UNIX signal instead of simply killing the process. DISCLAIMER: This bypasses Pueue's process handling logic! You might enter weird invalid states, use at your own descretion --help(-h) # Print help ] # Send something to a task. Useful for sending confirmations such as 'y\n' export extern "pueue send" [ task_id: string # The id of the task input: string # The input that should be sent to the process --help(-h) # Print help ] # Edit the command, path, label, or priority of a stashed or queued task. By default only the command is edited. Multiple properties can be added in one go. export extern "pueue edit" [ task_id: string # The task's id --command(-c) # Edit the task's command --path(-p) # Edit the task's path --label(-l) # Edit the task's label --priority(-o) # Edit the task's priority --help(-h) # Print help ] # Use this to add or remove groups. By default, this will simply display all known groups. export extern "pueue group" [ --json(-j) # Print the list of groups as json --help(-h) # Print help ] # Add a group by name export extern "pueue group add" [ name: string --parallel(-p): string # Set the amount of parallel tasks this group can have. Setting this to 0 means an unlimited amount of parallel tasks --help(-h) # Print help ] # Remove a group by name. This will move all tasks in this group to the default group! export extern "pueue group remove" [ name: string --help(-h) # Print help ] # Print this message or the help of the given subcommand(s) export extern "pueue group help" [ ] # Add a group by name export extern "pueue group help add" [ ] # Remove a group by name. This will move all tasks in this group to the default group! export extern "pueue group help remove" [ ] # Print this message or the help of the given subcommand(s) export extern "pueue group help help" [ ] # Display the current status of all tasks export extern "pueue status" [ ...query: string # Users can specify a custom query to filter for specific values, order by a column or limit the amount of tasks listed. Use `--help` for the full syntax definition --json(-j) # Print the current state as json to stdout. This does not include the output of tasks. Use `log -j` if you want everything --group(-g): string # Only show tasks of a specific group --help(-h) # Print help (see more with '--help') ] # Accept a list or map of JSON pueue tasks via stdin and display it just like "pueue status". A simple example might look like this: pueue status --json | jq -c '.tasks' | pueue format-status export extern "pueue format-status" [ --group(-g): string # Only show tasks of a specific group --help(-h) # Print help ] # Display the log output of finished tasks. Only the last few lines will be shown by default. If you want to follow the output of a task, please use the "follow" subcommand. export extern "pueue log" [ ...task_ids: string # View the task output of these specific tasks --json(-j) # Print the resulting tasks and output as json. By default only the last lines will be returned unless --full is provided. Take care, as the json cannot be streamed! If your logs are really huge, using --full can use all of your machine's RAM --lines(-l): string # Only print the last X lines of each task's output. This is done by default if you're looking at multiple tasks --full(-f) # Show the whole output --help(-h) # Print help ] # Follow the output of a currently running task. This command works like "tail -f" export extern "pueue follow" [ task_id?: string # The id of the task you want to watch. If no or multiple tasks are running, you have to specify the id. If only a single task is running, you can omit the id --lines(-l): string # Only print the last X lines of the output before following --help(-h) # Print help ] # Wait until tasks are finished. By default, this will wait for all tasks in the default group to finish. Note: This will also wait for all tasks that aren't somehow 'Done'. Includes: [Paused, Stashed, Locked, Queued, ...] export extern "pueue wait" [ ...task_ids: string # This allows you to wait for specific tasks to finish --group(-g): string # Wait for all tasks in a specific group --all(-a) # Wait for all tasks across all groups and the default group --quiet(-q) # Don't show any log output while waiting --status(-s): string # Wait for tasks to reach a specific task status --help(-h) # Print help ] # Remove all finished tasks from the list export extern "pueue clean" [ --successful-only(-s) # Only clean tasks that finished successfully --group(-g): string # Only clean tasks of a specific group --help(-h) # Print help ] # Kill all tasks, clean up afterwards and reset EVERYTHING! export extern "pueue reset" [ --children(-c) # Deprecated: this switch no longer has any effect --force(-f) # Don't ask for any confirmation --help(-h) # Print help ] # Remotely shut down the daemon. Should only be used if the daemon isn't started by a service manager export extern "pueue shutdown" [ --help(-h) # Print help ] # Set the amount of allowed parallel tasks By default, adjusts the amount of the default group. No tasks will be stopped, if this is lowered. This limit is only considered when tasks are scheduled. export extern "pueue parallel" [ parallel_tasks?: string # The amount of allowed parallel tasks. Setting this to 0 means an unlimited amount of parallel tasks --group(-g): string # Set the amount for a specific group --help(-h) # Print help ] def "nu-complete pueue completions shell" [] { [ "bash" "elvish" "fish" "power-shell" "zsh" "nushell" ] } # Generates shell completion files. This can be ignored during normal operations export extern "pueue completions" [ shell: string@"nu-complete pueue completions shell" # The target shell output_directory?: string # The output directory to which the file should be written --help(-h) # Print help ] # Print this message or the help of the given subcommand(s) export extern "pueue help" [ ] # Enqueue a task for execution. There're many different options when scheduling a task. Check the individual option help texts for more information. Furthermore, please remember that scheduled commands are executed via your system shell. This means that the command needs proper shell escaping. The safest way to preserve shell escaping is to surround your command with quotes, for example: pueue add 'ls $HOME && echo "Some string"' export extern "pueue help add" [ ] # Remove tasks from the list. Running or paused tasks need to be killed first export extern "pueue help remove" [ ] # Switches the queue position of two commands. Only works on queued and stashed commands export extern "pueue help switch" [ ] # Stashed tasks won't be automatically started. You have to enqueue them or start them by hand export extern "pueue help stash" [ ] # Enqueue stashed tasks. They'll be handled normally afterwards export extern "pueue help enqueue" [ ] # Resume operation of specific tasks or groups of tasks. By default, this resumes the default group and all its tasks. Can also be used force-start specific tasks. export extern "pueue help start" [ ] # Restart failed or successful task(s). By default, identical tasks will be created and enqueued, but it's possible to restart in-place. You can also edit a few properties, such as the path and the command, before restarting. export extern "pueue help restart" [ ] # Either pause running tasks or specific groups of tasks. By default, pauses the default group and all its tasks. A paused queue (group) won't start any new tasks. export extern "pueue help pause" [ ] # Kill specific running tasks or whole task groups.. Kills all tasks of the default group when no ids or a specific group are provided. export extern "pueue help kill" [ ] # Send something to a task. Useful for sending confirmations such as 'y\n' export extern "pueue help send" [ ] # Edit the command, path, label, or priority of a stashed or queued task. By default only the command is edited. Multiple properties can be added in one go. export extern "pueue help edit" [ ] # Use this to add or remove groups. By default, this will simply display all known groups. export extern "pueue help group" [ ] # Add a group by name export extern "pueue help group add" [ ] # Remove a group by name. This will move all tasks in this group to the default group! export extern "pueue help group remove" [ ] # Display the current status of all tasks export extern "pueue help status" [ ] # Accept a list or map of JSON pueue tasks via stdin and display it just like "pueue status". A simple example might look like this: pueue status --json | jq -c '.tasks' | pueue format-status export extern "pueue help format-status" [ ] # Display the log output of finished tasks. Only the last few lines will be shown by default. If you want to follow the output of a task, please use the "follow" subcommand. export extern "pueue help log" [ ] # Follow the output of a currently running task. This command works like "tail -f" export extern "pueue help follow" [ ] # Wait until tasks are finished. By default, this will wait for all tasks in the default group to finish. Note: This will also wait for all tasks that aren't somehow 'Done'. Includes: [Paused, Stashed, Locked, Queued, ...] export extern "pueue help wait" [ ] # Remove all finished tasks from the list export extern "pueue help clean" [ ] # Kill all tasks, clean up afterwards and reset EVERYTHING! export extern "pueue help reset" [ ] # Remotely shut down the daemon. Should only be used if the daemon isn't started by a service manager export extern "pueue help shutdown" [ ] # Set the amount of allowed parallel tasks By default, adjusts the amount of the default group. No tasks will be stopped, if this is lowered. This limit is only considered when tasks are scheduled. export extern "pueue help parallel" [ ] # Generates shell completion files. This can be ignored during normal operations export extern "pueue help completions" [ ] # Print this message or the help of the given subcommand(s) export extern "pueue help help" [ ]}export use completions *+233 / −233 text lines
import static java.lang.System.out;import static java.nio.file.StandardOpenOption.CREATE_NEW;import static java.nio.file.StandardOpenOption.READ;import static java.nio.file.StandardOpenOption.WRITE;import java.nio.file.*;import java.nio.charset.*;import java.nio.*;import java.io.*;import java.security.*;import javax.crypto.*;import javax.crypto.spec.*;class aes { enum Command { ENCRYPT, DECRYPT } static Cipher AES_GCM_PKCS5; static byte[] SALT = new byte[] { 116, 104, 101, 32, 109, 111, 111, 110, 32, 105, 115, 32, 104, 105, 100, 100, 101, 110, 32, 105, 110, 32, 112, 108, 97, 105, 110, 32, 118, 105, 101, 119 }; static SecureRandom RANDOM = new SecureRandom(); /* * 12 ist NIST recommendation. supposedly fast and secure enough... */ static int GCM_IV_SIZE = 12; /* * AES encrypts 128-blocks internally, so this should be reasonable memory bufer * size. */ static int READ_BUFFER_SIZE = 128; /* * Supported sizes for GCM authentication tags seem to be {128, 120, 112, 104, * 96}. * But we do not really care, since we do not use them here. */ static int GCM_AUTH_TAG_SIZE = 96; public static void main(String[] arguments) throws Throwable { if (arguments.length == 0) { usage(); throw fail(); } var input_command = arguments[0]; Command command; if ("encrypt".startsWith(input_command)) { command = Command.ENCRYPT; } else if ("decrypt".startsWith(input_command)) { command = Command.DECRYPT; } else { throw fail("unknown command %s given%n", emphasize_global(input_command)); } AES_GCM_PKCS5 = Cipher.getInstance("AES/GCM/NoPadding"); var console = System.console(); /* * If there is no console, this program is most likely part of a pipe. * In such cases a `--password-file` flag is mandatory, because we cannot * interactively ask for the password. */ if (console == null) { if (arguments.length != 3 || !"--password-file".equals(arguments[1])) { usage(); throw fail( "When running %s non-interactively, the %s flag is required.%nOtherwise there is no way to securely obtain the password.%n", emphasize_local("aes"), emphasize_global("--password-file")); } var password_file = Path.of(arguments[2]); if (!Files.exists(password_file)) { throw fail("the given password file %s does not exist%n", emphasize_local(password_file.toString())); } var password = toChars(Files.readAllBytes(password_file)); switch (command) { case ENCRYPT: encrypt(password, System.in, System.out); break; case DECRYPT: decrypt(password, System.in, System.out); break; } } else { if (arguments.length <= 1) { usage(); throw fail("not enough arguments given%n"); } char[] password; String input; String output; if ("--password-file".equals(arguments[1])) { if (arguments.length != 5) { usage(); throw fail("the flag %s requires a path%n", emphasize_local("--password-file")); } var password_file = Path.of(arguments[2]); if (!Files.exists(password_file)) { throw fail("the given password file %s does not exist%n", emphasize_local(password_file.toString())); } password = toChars(Files.readAllBytes(password_file)); input = arguments[3]; output = arguments[4]; } else { if (arguments.length != 3) { usage(); throw fail("when encrypting/decrypting a file, an output path is required%n"); } password = console.readPassword("[%s]:", emphasize_global("Password")); input = arguments[1]; output = arguments[2]; } var input_path = Path.of(input); if (!Files.exists(input_path)) { throw fail("the given input path %s does not exist%n", emphasize_global(input_path.toString())); } var output_path = Path.of(output); if (Files.exists(output_path)) { throw fail("the output path %s already exists%n", emphasize_global(output_path.toString())); } try (var input_stream = Files.newInputStream(input_path, READ); var output_stream = Files.newOutputStream(output_path, CREATE_NEW, WRITE);) { switch (command) { case ENCRYPT: encrypt(password, input_stream, output_stream); break; case DECRYPT: decrypt(password, input_stream, output_stream); break; } } } throw exit(); } static void encrypt(char[] password, InputStream input, OutputStream output) throws Exception { // FIXME: generate random salt and append it here just like IV // in GCM the IV should be unique per encrypted thingy var initialization_vector = new byte[GCM_IV_SIZE]; RANDOM.nextBytes(initialization_vector); // save the IV for the decryption step later. secure? nope. but how else are we // to share IVs between encryption/decryption? output.write(initialization_vector); var secret = toSecretKey(password); var parameter_spec = new GCMParameterSpec(GCM_AUTH_TAG_SIZE, initialization_vector); AES_GCM_PKCS5.init(Cipher.ENCRYPT_MODE, secret, parameter_spec); var read_buffer = new byte[READ_BUFFER_SIZE]; var aes_buffer = new byte[READ_BUFFER_SIZE]; int read_bytes_count = 0; while ((read_bytes_count = input.read(read_buffer)) != -1) { var aes_bytes_count = AES_GCM_PKCS5.update(read_buffer, 0, read_bytes_count, aes_buffer); output.write(aes_buffer, 0, aes_bytes_count); } output.write(AES_GCM_PKCS5.doFinal()); } static void decrypt(char[] password, InputStream input, OutputStream output) throws Exception { // the IV get prepended to the data during encryption var initialization_vector = new byte[GCM_IV_SIZE]; input.read(initialization_vector); var parameter_spec = new GCMParameterSpec(GCM_AUTH_TAG_SIZE, initialization_vector); var secret = toSecretKey(password); AES_GCM_PKCS5.init(Cipher.DECRYPT_MODE, secret, parameter_spec); var read_buffer = new byte[READ_BUFFER_SIZE]; var aes_buffer = new byte[READ_BUFFER_SIZE]; int read_bytes_count = 0; while ((read_bytes_count = input.read(read_buffer)) != -1) { var aes_bytes_count = AES_GCM_PKCS5.update(read_buffer, 0, read_bytes_count, aes_buffer); output.write(aes_buffer, 0, aes_bytes_count); } // the java impl of GCM seems to buffer the whole data in memory and only // releasing it on doFinal. yuck! // there is not much i can do about this other than to wait for JDK patches. // TODO: in the case of AES GCM the final byte block is the authentication tag. // as such it should porbably NOT be written to the output file. // or is this assumption wrong? output.write(AES_GCM_PKCS5.doFinal()); // FIXME: when given a wrong password we get a nonsensical error. make this // nicer for human } static SecretKey toSecretKey(char[] password) throws Exception { var factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256"); var spec = new PBEKeySpec(password, SALT, 65536, 256); return new SecretKeySpec(factory.generateSecret(spec).getEncoded(), "AES"); } static char[] toChars(byte[] bytes) { var byte_buffer = ByteBuffer.wrap(bytes); var char_buffer = StandardCharsets.UTF_8.decode(byte_buffer); return char_buffer.array(); } static void usage() { out.printf("%s encrypts/decrypts data.%n", emphasize_local("Symmetrically ")); out.printf("%s: java aes.java <e(ncrypt)|d(ecrypt)> [--password-file <path>] <input path> <output path>%n", emphasize_global("Usage for files")); out.printf("%s: java aes.java <e(ncrypt)|d(ecrypt)> --password-file <path>%n", emphasize_global("Usage for stdin/stdout")); } static Throwable exit() { System.exit(0); // abuse control flow to make compiler realize `exit` will never return return new Throwable(); } static String emphasize_global(String message) { return "\033[4m" + message + "\033[0m"; } static String emphasize_local(String message) { return "\033[3m" + message + "\033[0m"; } static Throwable fail(String message, Object... arguments) { out.printf(message, arguments); System.exit(-1); // abuse control flow to make compiler realize `fail` will never return return new Throwable(); } static Throwable fail() { System.exit(-1); // abuse control flow to make compiler realize `fail` will never return return new Throwable(); }}import static java.lang.System.out;
import static java.nio.file.StandardOpenOption.CREATE_NEW;
import static java.nio.file.StandardOpenOption.READ;
import static java.nio.file.StandardOpenOption.WRITE;
import java.nio.file.*;
import java.nio.charset.*;
import java.nio.*;
import java.io.*;
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
class aes {
enum Command {
ENCRYPT, DECRYPT
}
static Cipher AES_GCM_PKCS5;
static byte[] SALT = new byte[] { 116, 104, 101, 32, 109, 111, 111, 110, 32, 105, 115, 32, 104, 105, 100, 100, 101,
110, 32, 105, 110, 32, 112, 108, 97, 105, 110, 32, 118, 105, 101, 119 };
static SecureRandom RANDOM = new SecureRandom();
/*
* 12 ist NIST recommendation. supposedly fast and secure enough...
*/
static int GCM_IV_SIZE = 12;
/*
* AES encrypts 128-blocks internally, so this should be reasonable memory bufer
* size.
*/
static int READ_BUFFER_SIZE = 128;
/*
* Supported sizes for GCM authentication tags seem to be {128, 120, 112, 104,
* 96}.
* But we do not really care, since we do not use them here.
*/
static int GCM_AUTH_TAG_SIZE = 96;
public static void main(String[] arguments) throws Throwable {
if (arguments.length == 0) {
usage();
throw fail();
}
var input_command = arguments[0];
Command command;
if ("encrypt".startsWith(input_command)) {
command = Command.ENCRYPT;
} else if ("decrypt".startsWith(input_command)) {
command = Command.DECRYPT;
} else {
throw fail("unknown command %s given%n", emphasize_global(input_command));
}
AES_GCM_PKCS5 = Cipher.getInstance("AES/GCM/NoPadding");
var console = System.console();
/*
* If there is no console, this program is most likely part of a pipe.
* In such cases a `--password-file` flag is mandatory, because we cannot
* interactively ask for the password.
*/
if (console == null) {
if (arguments.length != 3 || !"--password-file".equals(arguments[1])) {
usage();
throw fail(
"When running %s non-interactively, the %s flag is required.%nOtherwise there is no way to securely obtain the password.%n",
emphasize_local("aes"), emphasize_global("--password-file"));
}
var password_file = Path.of(arguments[2]);
if (!Files.exists(password_file)) {
throw fail("the given password file %s does not exist%n", emphasize_local(password_file.toString()));
}
var password = toChars(Files.readAllBytes(password_file));
switch (command) {
case ENCRYPT:
encrypt(password, System.in, System.out);
break;
case DECRYPT:
decrypt(password, System.in, System.out);
break;
}
} else {
if (arguments.length <= 1) {
usage();
throw fail("not enough arguments given%n");
}
char[] password;
String input;
String output;
if ("--password-file".equals(arguments[1])) {
if (arguments.length != 5) {
usage();
throw fail("the flag %s requires a path%n", emphasize_local("--password-file"));
}
var password_file = Path.of(arguments[2]);
if (!Files.exists(password_file)) {
throw fail("the given password file %s does not exist%n", emphasize_local(password_file.toString()));
}
password = toChars(Files.readAllBytes(password_file));
input = arguments[3];
output = arguments[4];
} else {
if (arguments.length != 3) {
usage();
throw fail("when encrypting/decrypting a file, an output path is required%n");
}
password = console.readPassword("[%s]:", emphasize_global("Password"));
input = arguments[1];
output = arguments[2];
}
var input_path = Path.of(input);
if (!Files.exists(input_path)) {
throw fail("the given input path %s does not exist%n", emphasize_global(input_path.toString()));
}
var output_path = Path.of(output);
if (Files.exists(output_path)) {
throw fail("the output path %s already exists%n", emphasize_global(output_path.toString()));
}
try (var input_stream = Files.newInputStream(input_path, READ);
var output_stream = Files.newOutputStream(output_path, CREATE_NEW, WRITE);) {
switch (command) {
case ENCRYPT:
encrypt(password, input_stream, output_stream);
break;
case DECRYPT:
decrypt(password, input_stream, output_stream);
break;
}
}
}
throw exit();
}
static void encrypt(char[] password, InputStream input, OutputStream output) throws Exception {
// FIXME: generate random salt and append it here just like IV
// in GCM the IV should be unique per encrypted thingy
var initialization_vector = new byte[GCM_IV_SIZE];
RANDOM.nextBytes(initialization_vector);
// save the IV for the decryption step later. secure? nope. but how else are we
// to share IVs between encryption/decryption?
output.write(initialization_vector);
var secret = toSecretKey(password);
var parameter_spec = new GCMParameterSpec(GCM_AUTH_TAG_SIZE, initialization_vector);
AES_GCM_PKCS5.init(Cipher.ENCRYPT_MODE, secret, parameter_spec);
var read_buffer = new byte[READ_BUFFER_SIZE];
var aes_buffer = new byte[READ_BUFFER_SIZE];
int read_bytes_count = 0;
while ((read_bytes_count = input.read(read_buffer)) != -1) {
var aes_bytes_count = AES_GCM_PKCS5.update(read_buffer, 0, read_bytes_count, aes_buffer);
output.write(aes_buffer, 0, aes_bytes_count);
}
output.write(AES_GCM_PKCS5.doFinal());
}
static void decrypt(char[] password, InputStream input, OutputStream output) throws Exception {
// the IV get prepended to the data during encryption
var initialization_vector = new byte[GCM_IV_SIZE];
input.read(initialization_vector);
var parameter_spec = new GCMParameterSpec(GCM_AUTH_TAG_SIZE, initialization_vector);
var secret = toSecretKey(password);
AES_GCM_PKCS5.init(Cipher.DECRYPT_MODE, secret, parameter_spec);
var read_buffer = new byte[READ_BUFFER_SIZE];
var aes_buffer = new byte[READ_BUFFER_SIZE];
int read_bytes_count = 0;
while ((read_bytes_count = input.read(read_buffer)) != -1) {
var aes_bytes_count = AES_GCM_PKCS5.update(read_buffer, 0, read_bytes_count, aes_buffer);
output.write(aes_buffer, 0, aes_bytes_count);
}
// the java impl of GCM seems to buffer the whole data in memory and only
// releasing it on doFinal. yuck!
// there is not much i can do about this other than to wait for JDK patches.
// TODO: in the case of AES GCM the final byte block is the authentication tag.
// as such it should porbably NOT be written to the output file.
// or is this assumption wrong?
output.write(AES_GCM_PKCS5.doFinal());
// FIXME: when given a wrong password we get a nonsensical error. make this
// nicer for human
}
static SecretKey toSecretKey(char[] password) throws Exception {
var factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
var spec = new PBEKeySpec(password, SALT, 65536, 256);
return new SecretKeySpec(factory.generateSecret(spec).getEncoded(), "AES");
}
static char[] toChars(byte[] bytes) {
var byte_buffer = ByteBuffer.wrap(bytes);
var char_buffer = StandardCharsets.UTF_8.decode(byte_buffer);
return char_buffer.array();
}
static void usage() {
out.printf("%s encrypts/decrypts data.%n", emphasize_local("Symmetrically "));
out.printf("%s: java aes.java <e(ncrypt)|d(ecrypt)> [--password-file <path>] <input path> <output path>%n",
emphasize_global("Usage for files"));
out.printf("%s: java aes.java <e(ncrypt)|d(ecrypt)> --password-file <path>%n",
emphasize_global("Usage for stdin/stdout"));
}
static Throwable exit() {
System.exit(0);
// abuse control flow to make compiler realize `exit` will never return
return new Throwable();
}
static String emphasize_global(String message) {
return "\033[4m" + message + "\033[0m";
}
static String emphasize_local(String message) {
return "\033[3m" + message + "\033[0m";
}
static Throwable fail(String message, Object... arguments) {
out.printf(message, arguments);
System.exit(-1);
// abuse control flow to make compiler realize `fail` will never return
return new Throwable();
}
static Throwable fail() {
System.exit(-1);
// abuse control flow to make compiler realize `fail` will never return
return new Throwable();
}
}
new file mode 100644+60 / −0 text lines
name;bin;cargo_args
asm-cli-rust; asm-cli-rust; --git https://github.com/cch123/asm-cli-rust
bat
bk
bottom; btm
cargo-cache
cargo-update;cargo-install-update
carl
calendar-rs;calendar
du-dust; dust
dotenv-linter
diskonaut
eva
emplace
eza; eza; --features vendored-openssl,vendored-libgit2
fend
fd-find;fd
git-delta;delta
gitu;gitu; --locked
gitoxide;gix
hexyl
hyperfine
inlyne
jj-cli; jj; --locked --bin jj
just
lms
lurk-cli; lurk
lychee;lychee; --locked --no-default-features --features rustls-tls,email-check
macchina
mdbook
mdcat
monolith
names
netscanner
neovide;neovide; --git https://github.com/neovide/neovide
nu;nu; --locked
nu_plugin_audio_hook; nu_plugin_audio_hook; --git https://github.com/FMotalleb/nu_plugin_audio_hook.git --features all-decoders
ouch
pastel
presenterm
pueue;pueue;--locked
ripgrep;rg
rbw
skim;sk
sbyte
sniffnet
taplo-cli;taplo; --locked --features lsp
tealdeer;tldr
tokei
topgrade
tsdl
ttyper
unison-fsmonitor
ugdb
vivid
wthrr
yazi-cli;ya; --locked
yazi-fm;yazi; --locked
zoxide
+198 / −198 text lines
import static java.lang.System.out;import java.io.*;import java.net.*;import java.net.http.*;import java.net.http.HttpResponse.*;import java.nio.file.*;import java.util.*;import java.util.concurrent.ConcurrentSkipListSet;class download_jar { public static void main(final String[] command_line_arguments) { help(); var current_working_directory = Paths.get(System.getProperty("user.dir")); var download_directory = current_working_directory.resolve("downloaded_artifacts"); var maven_repository = "https://repo.maven.apache.org/maven2"; var expected_count_of_arguments = 3; if (contains(command_line_arguments, "-d")) { expected_count_of_arguments = expected_count_of_arguments + 2; try { var given_download_directory = command_line_arguments[index_of(command_line_arguments, "-d") + 1]; download_directory = current_working_directory.resolve(given_download_directory); } catch (IndexOutOfBoundsException exception) { out.println("The -d option requires an argument."); usage(); fail(); } } if (contains(command_line_arguments, "-r")) { expected_count_of_arguments = expected_count_of_arguments + 2; try { var given_maven_repository = command_line_arguments[index_of(command_line_arguments, "-r") + 1]; maven_repository = given_maven_repository; } catch (IndexOutOfBoundsException exception) { out.println("The -r option requires an argument."); usage(); fail(); } } if (command_line_arguments.length != expected_count_of_arguments) { usage(); fail(); } var maven_coordinates_reversed = new String[3]; for (var index = 2; index >= 0; --index) { maven_coordinates_reversed[index] = command_line_arguments[expected_count_of_arguments - index - 1]; } var group_id = maven_coordinates_reversed[2]; var artifact_id = maven_coordinates_reversed[1]; var version = maven_coordinates_reversed[0]; if (Files.exists(download_directory) && Files.isRegularFile(download_directory)) { fail("The given download directory path %s already points to a file!%n", download_directory.toString()); } else if (!Files.exists(download_directory)) { out.printf("Creating directory at %s%n.", emphasize_global(download_directory.toString())); try { Files.createDirectories(download_directory); } catch (IOException __) { fail("Unable to create directory at %s", emphasize_global(download_directory.toString())); } } var expected_artifact_base_url = guess_maven_artifact_url(maven_repository, group_id, artifact_id, version); var client = HttpClient.newHttpClient(); var request = HttpRequest.newBuilder().uri(URI.create(expected_artifact_base_url)).build(); var target_directory = download_directory; client.sendAsync(request, BodyHandlers.ofString()).thenApply(HttpResponse::statusCode).thenAccept(status -> { if (status > 299) { fail("Could not find maven artifact at %s.%n", expected_artifact_base_url); } else { download_ressource(client, target_directory, build_ressource_url(expected_artifact_base_url, artifact_id, version, ".jar")); download_ressource(client, target_directory, build_ressource_url(expected_artifact_base_url, artifact_id, version, "-sources.jar")); // FIXME BLOCKER! How do we implement the version clash resolution? // Preferably in a manner that avoids pointless downloads... var processed_cache = new ConcurrentSkipListSet<String>(); process_pom(client, processed_cache, build_ressource_url(expected_artifact_base_url, artifact_id, version, ".pom")); } }).join(); out.printf("download directory:\t%s%nmaven repository:\t%s%nmaven coordinates:\t%s:%s:%s%n", emphasize_global(download_directory.toString()), emphasize_global(maven_repository), emphasize_global(group_id), emphasize_global(artifact_id), emphasize_global(version)); exit(); } static Collection<String> process_pom(HttpClient client, Set<String> processed, String pom_url) { if (processed.contains(pom_url)) return Collections.emptyList(); var request = HttpRequest.newBuilder().uri(URI.create(pom_url)).build(); return client.sendAsync(request, BodyHandlers.ofInputStream()).thenApply(input -> { // TODO add pom to list of processed so that a pom only ever gets read once processed.add(pom_url); // TODO traverse path to root of poms and collect managed dependencies // TODO collect declared dependencies from given pom return List.<String>of(); }).join(); } static void download_ressource(HttpClient client, Path target_directory, String ressource_url) { var request = HttpRequest.newBuilder().uri(URI.create(ressource_url)).build(); var ressource_name = ressource_url.substring(ressource_url.lastIndexOf('/') + 1); var target_ressource_path = target_directory.resolve(ressource_name); client.sendAsync(request, BodyHandlers.ofFile(target_ressource_path)).join(); } static String build_ressource_url(String base, String artifact_id, String version, String suffix) { var url = new StringBuilder(base); if (!base.endsWith("/")) url.append('/'); url.append(artifact_id); url.append('-'); url.append(version); url.append(suffix); return url.toString(); } static String guess_maven_artifact_url(String base, String group_id, String artifact_id, String version) { var url = new StringBuilder(base); if (!base.endsWith("/")) url.append('/'); url.append(group_id.replaceAll("\\.", "\\/")); url.append('/'); url.append(artifact_id); url.append('/'); url.append(version); url.append('/'); return url.toString(); } static class Dependency { String artifactId; String groupId; String version; String scope; boolean optional; } static <T> int index_of(T[] array, T item) { var length = array.length; if (length == 0) return -1; for (var index = 0; index < length; ++index) { var element = array[index]; if (Objects.equals(element, item)) return index; } return -1; } @SafeVarargs static <T> boolean contains(T[] array, T... items) { if (array.length == 0) return false; if (items.length == 0) return false; for (var element : array) { for (var argument : items) { if (element.equals(argument)) return true; } } return false; } static void help() { out.printf("Downloads an artifact from a %s repository with its %s.%n", emphasize_local("maven"), emphasize_local("transitive dependencies")); } static void usage() { out.printf("%s: java download_jar.java <group id> <artifact id> <version>%n", emphasize_global("Usage")); } static void exit() { out.printf("%s!%n", emphasize_local("Done")); System.exit(0); } static String emphasize_global(String message) { return "\033[4m" + message + "\033[0m"; } static String emphasize_local(String message) { return "\033[3m" + message + "\033[0m"; } static void fail(String message, Object... arguments) { out.printf(message, arguments); System.exit(-1); } static void fail() { System.exit(-1); }}import static java.lang.System.out;
import java.io.*;
import java.net.*;
import java.net.http.*;
import java.net.http.HttpResponse.*;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.ConcurrentSkipListSet;
class download_jar {
public static void main(final String[] command_line_arguments) {
help();
var current_working_directory = Paths.get(System.getProperty("user.dir"));
var download_directory = current_working_directory.resolve("downloaded_artifacts");
var maven_repository = "https://repo.maven.apache.org/maven2";
var expected_count_of_arguments = 3;
if (contains(command_line_arguments, "-d")) {
expected_count_of_arguments = expected_count_of_arguments + 2;
try {
var given_download_directory = command_line_arguments[index_of(command_line_arguments, "-d") + 1];
download_directory = current_working_directory.resolve(given_download_directory);
} catch (IndexOutOfBoundsException exception) {
out.println("The -d option requires an argument.");
usage();
fail();
}
}
if (contains(command_line_arguments, "-r")) {
expected_count_of_arguments = expected_count_of_arguments + 2;
try {
var given_maven_repository = command_line_arguments[index_of(command_line_arguments, "-r") + 1];
maven_repository = given_maven_repository;
} catch (IndexOutOfBoundsException exception) {
out.println("The -r option requires an argument.");
usage();
fail();
}
}
if (command_line_arguments.length != expected_count_of_arguments) {
usage();
fail();
}
var maven_coordinates_reversed = new String[3];
for (var index = 2; index >= 0; --index) {
maven_coordinates_reversed[index] = command_line_arguments[expected_count_of_arguments - index - 1];
}
var group_id = maven_coordinates_reversed[2];
var artifact_id = maven_coordinates_reversed[1];
var version = maven_coordinates_reversed[0];
if (Files.exists(download_directory) && Files.isRegularFile(download_directory)) {
fail("The given download directory path %s already points to a file!%n", download_directory.toString());
} else if (!Files.exists(download_directory)) {
out.printf("Creating directory at %s%n.", emphasize_global(download_directory.toString()));
try {
Files.createDirectories(download_directory);
} catch (IOException __) {
fail("Unable to create directory at %s", emphasize_global(download_directory.toString()));
}
}
var expected_artifact_base_url = guess_maven_artifact_url(maven_repository, group_id, artifact_id, version);
var client = HttpClient.newHttpClient();
var request = HttpRequest.newBuilder().uri(URI.create(expected_artifact_base_url)).build();
var target_directory = download_directory;
client.sendAsync(request, BodyHandlers.ofString()).thenApply(HttpResponse::statusCode).thenAccept(status -> {
if (status > 299) {
fail("Could not find maven artifact at %s.%n", expected_artifact_base_url);
} else {
download_ressource(client, target_directory,
build_ressource_url(expected_artifact_base_url, artifact_id, version, ".jar"));
download_ressource(client, target_directory,
build_ressource_url(expected_artifact_base_url, artifact_id, version, "-sources.jar"));
// FIXME BLOCKER! How do we implement the version clash resolution?
// Preferably in a manner that avoids pointless downloads...
var processed_cache = new ConcurrentSkipListSet<String>();
process_pom(client, processed_cache,
build_ressource_url(expected_artifact_base_url, artifact_id, version, ".pom"));
}
}).join();
out.printf("download directory:\t%s%nmaven repository:\t%s%nmaven coordinates:\t%s:%s:%s%n",
emphasize_global(download_directory.toString()), emphasize_global(maven_repository), emphasize_global(group_id),
emphasize_global(artifact_id), emphasize_global(version));
exit();
}
static Collection<String> process_pom(HttpClient client, Set<String> processed, String pom_url) {
if (processed.contains(pom_url))
return Collections.emptyList();
var request = HttpRequest.newBuilder().uri(URI.create(pom_url)).build();
return client.sendAsync(request, BodyHandlers.ofInputStream()).thenApply(input -> {
// TODO add pom to list of processed so that a pom only ever gets read once
processed.add(pom_url);
// TODO traverse path to root of poms and collect managed dependencies
// TODO collect declared dependencies from given pom
return List.<String>of();
}).join();
}
static void download_ressource(HttpClient client, Path target_directory, String ressource_url) {
var request = HttpRequest.newBuilder().uri(URI.create(ressource_url)).build();
var ressource_name = ressource_url.substring(ressource_url.lastIndexOf('/') + 1);
var target_ressource_path = target_directory.resolve(ressource_name);
client.sendAsync(request, BodyHandlers.ofFile(target_ressource_path)).join();
}
static String build_ressource_url(String base, String artifact_id, String version, String suffix) {
var url = new StringBuilder(base);
if (!base.endsWith("/"))
url.append('/');
url.append(artifact_id);
url.append('-');
url.append(version);
url.append(suffix);
return url.toString();
}
static String guess_maven_artifact_url(String base, String group_id, String artifact_id, String version) {
var url = new StringBuilder(base);
if (!base.endsWith("/"))
url.append('/');
url.append(group_id.replaceAll("\\.", "\\/"));
url.append('/');
url.append(artifact_id);
url.append('/');
url.append(version);
url.append('/');
return url.toString();
}
static class Dependency {
String artifactId;
String groupId;
String version;
String scope;
boolean optional;
}
static <T> int index_of(T[] array, T item) {
var length = array.length;
if (length == 0)
return -1;
for (var index = 0; index < length; ++index) {
var element = array[index];
if (Objects.equals(element, item))
return index;
}
return -1;
}
@SafeVarargs
static <T> boolean contains(T[] array, T... items) {
if (array.length == 0)
return false;
if (items.length == 0)
return false;
for (var element : array) {
for (var argument : items) {
if (element.equals(argument))
return true;
}
}
return false;
}
static void help() {
out.printf("Downloads an artifact from a %s repository with its %s.%n", emphasize_local("maven"),
emphasize_local("transitive dependencies"));
}
static void usage() {
out.printf("%s: java download_jar.java <group id> <artifact id> <version>%n", emphasize_global("Usage"));
}
static void exit() {
out.printf("%s!%n", emphasize_local("Done"));
System.exit(0);
}
static String emphasize_global(String message) {
return "\033[4m" + message + "\033[0m";
}
static String emphasize_local(String message) {
return "\033[3m" + message + "\033[0m";
}
static void fail(String message, Object... arguments) {
out.printf(message, arguments);
System.exit(-1);
}
static void fail() {
System.exit(-1);
}
}
+337 / −337 text lines
#!/bin/sh## git-info - shows information about a Git repository a la `svn info'## How to use:# $ git info# $ git info ~/src/somewhere/somefile# $ git info some/relative/file_or_directory# $ git info ~/repos/something.git## Copyright (c) 2009-2022 Akinori MUSHA## All rights reserved.## Redistribution and use in source and binary forms, with or without# modification, are permitted provided that the following conditions# are met:# 1. Redistributions of source code must retain the above copyright# notice, this list of conditions and the following disclaimer.# 2. Redistributions in binary form must reproduce the above copyright# notice, this list of conditions and the following disclaimer in the# documentation and/or other materials provided with the distribution.## THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF# SUCH DAMAGE.#COLOR=main () { local opt local OPTS_SPEC="\$0 [<options>] [<path>]$0 shows information about a Git repository.--h,help show the helpcolor?when show colored output (always|never|auto)" eval "$(echo "$OPTS_SPEC" | git rev-parse --parseopt --stuck-long -- "$@" || echo exit $?)" while [ $# -gt 0 ]; do opt="$1" shift case "$opt" in --color) COLOR=always ;; --color\=*) COLOR="${opt#*=}" ;; --) break ;; *) die "Unexpected option: $opt" ;; esac done initialize_colors case "$#" in 1) ;; 0) if [ -n "$GIT_DIR" ]; then set -- "$GIT_DIR" else set -- . fi ;; *) die "Too many arguments" ;; esac git_info "$1"}initialize_colors () { if [ -z "$COLOR" ]; then if git config --get-colorbool color.info; then COLOR=always else COLOR=never fi fi case "$COLOR" in always|never) COLOR_BRANCH=$COLOR ;; auto) if git config --get-colorbool color.branch; then COLOR_BRANCH=always else COLOR_BRANCH=never fi ;; *) die "option \`color' expects \"always\", \"auto\", or \"never\"" ;; esac if [ "$COLOR" = always ]; then REMOTE_COLOR="$(get_color color.info.remote color.branch.remote red)" LOCAL_COLOR="$(get_color color.info.local color.branch.local green)" PATH_COLOR="$(get_color color.info.path '' 'bold')" REPOSITORY_COLOR="$(get_color color.info.repository '' 'bold')" ID_COLOR="$(get_color color.info.id '' 'yellow')" RESET_COLOR=$(printf "\033[m") else REMOTE_COLOR= LOCAL_COLOR= PATH_COLOR= REPOSITORY_COLOR= ID_COLOR= RESET_COLOR= fi}get_color () { local key1="$1" key2="$2" fb="$3" local color="$(git config --get-color "$key1" '')" case "$color" in '[m'|'') git config --get-color "$key2" "$fb" ;; *) printf '%s' "$color" ;; esac}git_info () { local path="$1" dir relpath root git_dir if [ -d "$path" ]; then dir="$(cd -P "$path" && pwd)" || die "$path: Cannot cd to the directory" case "$path" in *.git) git_dir="$dir" ;; esac elif [ -f "$path" ]; then dir="$(dirname "$path")" dir="$(cd -P "$dir" && pwd)" || die "$dir: Cannot cd to the directory" relpath="$(basename "$path")" else die "$path: No such file or directory" fi if [ -n "$git_dir" ]; then dir= relpath= elif case "$dir" in ?*.git) [ -d "$dir/objects" -a -d "$dir/refs" ] ;; *) false ;; esac; then git_dir="$dir" relpath= else root="$( cd "$dir" || exit 1 while [ ! -e .git ]; do [ "$(pwd)" = / ] && exit 1 cd .. done pwd )" || die "Not a git repository." git_dir="$root/.git" if [ "$dir" = "$root" ]; then relpath=. elif [ -n "$relpath" ]; then relpath="${dir#"$root/"}/$relpath" else relpath="${dir#"$root/"}" fi fi set -- "$git_dir" if [ -n "$relpath" ]; then set -- "$@" "$relpath" fi do_git_info "$@"}do_git_info () { local git_dir="$1" relpath="$2" root line field color reset shift echo "Repository Path: $PATH_COLOR$git_dir$RESET_COLOR" if [ $# -gt 0 ]; then root="$(dirname "$git_dir")" if [ "$relpath" = . ]; then echo "Path: $PATH_COLOR$root$RESET_COLOR" else echo "Path: $PATH_COLOR$root/$relpath$RESET_COLOR" fi fi maketemp GIT_DIR="$git_dir" git remote -v > "$TEMPFILE" if [ -s "$TEMPFILE" ]; then echo "Remote Repositories:" sed -e "s/^\([^ ]\{1,\}\)\([ ]\{1,\}\)\([^ ]\{1,\}\)/$REMOTE_COLOR\1$RESET_COLOR\2$REPOSITORY_COLOR\3$RESET_COLOR/" \ -e 's/^/ /' \ "$TEMPFILE" fi GIT_DIR="$git_dir" git branch -r --color=$COLOR_BRANCH > "$TEMPFILE" if [ -s "$TEMPFILE" ]; then echo "Remote Branches:" sed -e "s/\([ ]\{1,\}->[ ]\{1,\}\)\([^ ]\{1,\}\)/\1$REMOTE_COLOR\2$RESET_COLOR/" \ -e 's/^ */ /' "$TEMPFILE" fi GIT_DIR="$git_dir" git branch --color=$COLOR_BRANCH > "$TEMPFILE" if [ -s "$TEMPFILE" ]; then echo "Local Branches:" sed 's/^/ /' "$TEMPFILE" fi echo "Repository Configuration:" GIT_DIR="$git_dir" git config --local --list | sort | { prev_section= prev_subsection= while read line; do case "$line" in (*=*) lhs=$(expr "$line" : '\([^=]\{1,\}\)') rhs=$(expr "$line" : '[^=]\{1,\}=\(.*\)') case "$lhs" in (?*.?*.?*) section=$(expr "$lhs" : '\([^.]\{1,\}\)') subsection=$(expr "$lhs" : '[^.]\{1,\}\.\(.\{1,\}\)\.') key=$(expr "$lhs" : '[^.]\{1,\}\..\{1,\}\.\([^.]\{0,\}\)$') if [ "$section" != "$prev_section" -o "$subsection" != "$prev_subsection" ]; then prev_section=$section prev_subsection=$subsection case "$section" in (remote) subsection=$REMOTE_COLOR$subsection$RESET_COLOR ;; (branch) subsection=$LOCAL_COLOR$subsection$RESET_COLOR esac printf "\t[%s \"%s\"]\n" "$section" "$subsection" fi case "$section" in (remote) if [ "$key" = url ]; then rhs=$REPOSITORY_COLOR$rhs$RESET_COLOR fi ;; (branch) if [ "$key" = remote ]; then rhs=$REMOTE_COLOR$rhs$RESET_COLOR fi esac printf "\t\t%s = %s\n" "$key" "$rhs" ;; (?*.?*) section=$(expr "$lhs" : '\([^.]\{1,\}\)') key=$(expr "$lhs" : '[^.]\{1,\}\.\([^.]\{1,\}\)$') if [ "$section" != "$prev_section" -o -n "$prev_subsection" ]; then prev_section=$section prev_subsection= printf "\t[%s]\n" "$section" fi printf "\t\t$key = $rhs\n" ;; (*) esac esac done } (cd "$root" && GIT_DIR="$git_dir" git log --max-count=1 "$@") | { while read -r field line; do color= reset= case "$field" in commit) field='Commit ID:' color="$ID_COLOR" reset="$RESET_COLOR" ;; *:) ;; '') break ;; esac echo "Last Changed $field $color$line$reset" done cat > "$TEMPFILE" } echo "Last Changed Log:" sed 's/^ / /' "$TEMPFILE" finalize}die () { [ "$#" -gt 0 ] && echo "$0: $@" >&2 finalize exit 1}TEMPFILE=maketemp () { if [ -z "$TEMPFILE" ]; then TEMPFILE="$(mktemp /tmp/git-info.XXXXXX)" || die trap "finalize; exit 130" 1 2 3 15 fi}finalize () { if [ -n "$TEMPFILE" ]; then rm -f "$TEMPFILE" fi}#!/bin/sh
#
# git-info - shows information about a Git repository a la `svn info'
#
# How to use:
# $ git info
# $ git info ~/src/somewhere/somefile
# $ git info some/relative/file_or_directory
# $ git info ~/repos/something.git
#
# Copyright (c) 2009-2022 Akinori MUSHA
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#
COLOR=
main () {
local opt
local OPTS_SPEC="\
$0 [<options>] [<path>]
$0 shows information about a Git repository.
--
h,help show the help
color?when show colored output (always|never|auto)
"
eval "$(echo "$OPTS_SPEC" | git rev-parse --parseopt --stuck-long -- "$@" || echo exit $?)"
while [ $# -gt 0 ]; do
opt="$1"
shift
case "$opt" in
--color)
COLOR=always
;;
--color\=*)
COLOR="${opt#*=}"
;;
--)
break
;;
*)
die "Unexpected option: $opt"
;;
esac
done
initialize_colors
case "$#" in
1)
;;
0)
if [ -n "$GIT_DIR" ]; then
set -- "$GIT_DIR"
else
set -- .
fi
;;
*)
die "Too many arguments"
;;
esac
git_info "$1"
}
initialize_colors () {
if [ -z "$COLOR" ]; then
if git config --get-colorbool color.info; then
COLOR=always
else
COLOR=never
fi
fi
case "$COLOR" in
always|never)
COLOR_BRANCH=$COLOR
;;
auto)
if git config --get-colorbool color.branch; then
COLOR_BRANCH=always
else
COLOR_BRANCH=never
fi
;;
*)
die "option \`color' expects \"always\", \"auto\", or \"never\""
;;
esac
if [ "$COLOR" = always ]; then
REMOTE_COLOR="$(get_color color.info.remote color.branch.remote red)"
LOCAL_COLOR="$(get_color color.info.local color.branch.local green)"
PATH_COLOR="$(get_color color.info.path '' 'bold')"
REPOSITORY_COLOR="$(get_color color.info.repository '' 'bold')"
ID_COLOR="$(get_color color.info.id '' 'yellow')"
RESET_COLOR=$(printf "\033[m")
else
REMOTE_COLOR=
LOCAL_COLOR=
PATH_COLOR=
REPOSITORY_COLOR=
ID_COLOR=
RESET_COLOR=
fi
}
get_color () {
local key1="$1" key2="$2" fb="$3"
local color="$(git config --get-color "$key1" '')"
case "$color" in
'[m'|'')
git config --get-color "$key2" "$fb"
;;
*)
printf '%s' "$color"
;;
esac
}
git_info () {
local path="$1" dir relpath root git_dir
if [ -d "$path" ]; then
dir="$(cd -P "$path" && pwd)" || die "$path: Cannot cd to the directory"
case "$path" in
*.git)
git_dir="$dir"
;;
esac
elif [ -f "$path" ]; then
dir="$(dirname "$path")"
dir="$(cd -P "$dir" && pwd)" || die "$dir: Cannot cd to the directory"
relpath="$(basename "$path")"
else
die "$path: No such file or directory"
fi
if [ -n "$git_dir" ]; then
dir=
relpath=
elif case "$dir" in ?*.git) [ -d "$dir/objects" -a -d "$dir/refs" ] ;; *) false ;; esac; then
git_dir="$dir"
relpath=
else
root="$(
cd "$dir" || exit 1
while [ ! -e .git ]; do
[ "$(pwd)" = / ] && exit 1
cd ..
done
pwd
)" || die "Not a git repository."
git_dir="$root/.git"
if [ "$dir" = "$root" ]; then
relpath=.
elif [ -n "$relpath" ]; then
relpath="${dir#"$root/"}/$relpath"
else
relpath="${dir#"$root/"}"
fi
fi
set -- "$git_dir"
if [ -n "$relpath" ]; then
set -- "$@" "$relpath"
fi
do_git_info "$@"
}
do_git_info () {
local git_dir="$1" relpath="$2" root line field color reset
shift
echo "Repository Path: $PATH_COLOR$git_dir$RESET_COLOR"
if [ $# -gt 0 ]; then
root="$(dirname "$git_dir")"
if [ "$relpath" = . ]; then
echo "Path: $PATH_COLOR$root$RESET_COLOR"
else
echo "Path: $PATH_COLOR$root/$relpath$RESET_COLOR"
fi
fi
maketemp
GIT_DIR="$git_dir" git remote -v > "$TEMPFILE"
if [ -s "$TEMPFILE" ]; then
echo "Remote Repositories:"
sed -e "s/^\([^ ]\{1,\}\)\([ ]\{1,\}\)\([^ ]\{1,\}\)/$REMOTE_COLOR\1$RESET_COLOR\2$REPOSITORY_COLOR\3$RESET_COLOR/" \
-e 's/^/ /' \
"$TEMPFILE"
fi
GIT_DIR="$git_dir" git branch -r --color=$COLOR_BRANCH > "$TEMPFILE"
if [ -s "$TEMPFILE" ]; then
echo "Remote Branches:"
sed -e "s/\([ ]\{1,\}->[ ]\{1,\}\)\([^ ]\{1,\}\)/\1$REMOTE_COLOR\2$RESET_COLOR/" \
-e 's/^ */ /' "$TEMPFILE"
fi
GIT_DIR="$git_dir" git branch --color=$COLOR_BRANCH > "$TEMPFILE"
if [ -s "$TEMPFILE" ]; then
echo "Local Branches:"
sed 's/^/ /' "$TEMPFILE"
fi
echo "Repository Configuration:"
GIT_DIR="$git_dir" git config --local --list | sort | {
prev_section=
prev_subsection=
while read line; do
case "$line" in
(*=*)
lhs=$(expr "$line" : '\([^=]\{1,\}\)')
rhs=$(expr "$line" : '[^=]\{1,\}=\(.*\)')
case "$lhs" in
(?*.?*.?*)
section=$(expr "$lhs" : '\([^.]\{1,\}\)')
subsection=$(expr "$lhs" : '[^.]\{1,\}\.\(.\{1,\}\)\.')
key=$(expr "$lhs" : '[^.]\{1,\}\..\{1,\}\.\([^.]\{0,\}\)$')
if [ "$section" != "$prev_section" -o "$subsection" != "$prev_subsection" ]; then
prev_section=$section
prev_subsection=$subsection
case "$section" in
(remote)
subsection=$REMOTE_COLOR$subsection$RESET_COLOR
;;
(branch)
subsection=$LOCAL_COLOR$subsection$RESET_COLOR
esac
printf "\t[%s \"%s\"]\n" "$section" "$subsection"
fi
case "$section" in
(remote)
if [ "$key" = url ]; then
rhs=$REPOSITORY_COLOR$rhs$RESET_COLOR
fi
;;
(branch)
if [ "$key" = remote ]; then
rhs=$REMOTE_COLOR$rhs$RESET_COLOR
fi
esac
printf "\t\t%s = %s\n" "$key" "$rhs"
;;
(?*.?*)
section=$(expr "$lhs" : '\([^.]\{1,\}\)')
key=$(expr "$lhs" : '[^.]\{1,\}\.\([^.]\{1,\}\)$')
if [ "$section" != "$prev_section" -o -n "$prev_subsection" ]; then
prev_section=$section
prev_subsection=
printf "\t[%s]\n" "$section"
fi
printf "\t\t$key = $rhs\n"
;;
(*)
esac
esac
done
}
(cd "$root" && GIT_DIR="$git_dir" git log --max-count=1 "$@") | {
while read -r field line; do
color=
reset=
case "$field" in
commit)
field='Commit ID:'
color="$ID_COLOR"
reset="$RESET_COLOR"
;;
*:)
;;
'')
break
;;
esac
echo "Last Changed $field $color$line$reset"
done
cat > "$TEMPFILE"
}
echo "Last Changed Log:"
sed 's/^ / /' "$TEMPFILE"
finalize
}
die () {
[ "$#" -gt 0 ] && echo "$0: $@" >&2
finalize
exit 1
}
TEMPFILE=
maketemp () {
if [ -z "$TEMPFILE" ]; then
TEMPFILE="$(mktemp /tmp/git-info.XXXXXX)" || die
trap "finalize; exit 130" 1 2 3 15
fi
}
finalize () {
if [ -n "$TEMPFILE" ]; then
rm -f "$TEMPFILE"
fi
}
+17 / −17 text lines
#!/usr/bin/env nudef main [] { const background_settings = [ ['key', 'value']; ['picture-uri', 'none'] ['color-shading-type', 'solid'] ['primary-color', '#131313'] ['secondary-color', '#131313'] ] $background_settings | each { | setting | run-external gsettings set 'org.gnome.desktop.background' $setting.key $setting.value } null}#!/usr/bin/env nu
def main [] {
const background_settings = [
['key', 'value'];
['picture-uri', 'none']
['color-shading-type', 'solid']
['primary-color', '#131313']
['secondary-color', '#131313']
]
$background_settings | each { | setting |
run-external gsettings set 'org.gnome.desktop.background' $setting.key $setting.value
}
null
}
+146 / −146 text lines
import static java.lang.System.out;import static java.lang.System.err;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths;import java.util.Arrays;final class install { // TODO: platform key in die csv, um os zu unterscheiden. static final String CARGO_PACKAGES_CSV_FILE = "tools.csv"; public static void main(String[] __) throws Throwable { exec("cargo", "--version"); var csv = Path.of(CARGO_PACKAGES_CSV_FILE); if (!Files.exists(csv)) { throw fail("Expected a CSV file with cargo crates!"); } var lines = Files.lines(csv).toArray(String[]::new); for (int index = 1; index < lines.length; ++index) { var line = lines[index]; var spec = parse(line); if (spec != null && !which(spec.bin)) { install(spec); } } } static boolean which(String program) { var pathEnv = System.getenv("PATH"); if (pathEnv == null || pathEnv.isEmpty()) { return false; } var paths = pathEnv.split(System.getProperty("path.separator")); var extensions = new String[] { "", ".exe", ".bat", ".cmd", ".com" }; for (var path : paths) { for (var extension : extensions) { var fullPath = Paths.get(path, program + extension); if (Files.exists(fullPath) && Files.isExecutable(fullPath)) { return true; } } } return false; } static void exec(String... command) throws Throwable { var proc = new ProcessBuilder(command).inheritIO().start(); proc.waitFor(); var exit = proc.exitValue(); if (exit != 0) { throw fail("process failed to exec with code %d.%nproc: %s", exit, emphasize_local(Arrays.toString(command))); } } static void install(Spec spec) throws Throwable { out("cargo install %s (%s) %s", emphasize_global(spec.name), emphasize_local(spec.bin), emphasize_local(Arrays.toString(spec.flags))); var cmd = new String[3 + spec.flags.length]; cmd[0] = "cargo"; cmd[1] = "install"; cmd[2] = spec.name; System.arraycopy(spec.flags, 0, cmd, 3, spec.flags.length); exec(cmd); } record Spec(String name, String bin, String... flags) { }; static Spec parse(String line) throws Throwable { if (line.startsWith("#")) { return null; } var by_comma = line.split(";"); if (by_comma.length == 0) { throw fail("empty line in CSV"); } if (by_comma.length > 3) { throw fail("line in CSV should have 1-3 fields%nfound: %s", emphasize_local(line)); } var name = by_comma[0].strip(); var bin = name; if (by_comma.length > 1) { bin = by_comma[1].strip(); } var flags = new String[] {}; if (by_comma.length == 3) { flags = by_comma[2].strip().split(" "); } return new Spec(name, bin, flags); } static void out(String fmt, Object... args) { out.printf(fmt, args); out.println(); } static void dbg(String fmt, Object... args) { System.err.print("[DBG]: "); System.err.printf(fmt, args); System.err.println(); } static Throwable exit() { System.exit(0); // abuse control flow to make compiler realize `exit` will never return return new Throwable(); } static String emphasize_global(String message) { return "\033[4m" + message + "\033[0m"; } static String emphasize_local(String message) { return "\033[3m" + message + "\033[0m"; } static Throwable fail(String message, Object... arguments) { err.printf(message, arguments); System.exit(-1); // abuse control flow to make compiler realize `fail` will never return return new Throwable(); } static Throwable fail() { System.exit(-1); // abuse control flow to make compiler realize `fail` will never return return new Throwable(); }}import static java.lang.System.out;
import static java.lang.System.err;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
final class install {
// TODO: platform key in die csv, um os zu unterscheiden.
static final String CARGO_PACKAGES_CSV_FILE = "crates.csv";
public static void main(String[] __)
throws Throwable {
exec("cargo", "--version");
var csv = Path.of(CARGO_PACKAGES_CSV_FILE);
if (!Files.exists(csv)) {
throw fail("Expected a CSV file with cargo crates!");
}
var lines = Files.lines(csv).toArray(String[]::new);
for (int index = 1; index < lines.length; ++index) {
var line = lines[index];
var spec = parse(line);
if (spec != null && !which(spec.bin)) {
install(spec);
}
}
}
static boolean which(String program) {
var pathEnv = System.getenv("PATH");
if (pathEnv == null || pathEnv.isEmpty()) {
return false;
}
var paths = pathEnv.split(System.getProperty("path.separator"));
var extensions = new String[] { "", ".exe", ".bat", ".cmd", ".com" };
for (var path : paths) {
for (var extension : extensions) {
var fullPath = Paths.get(path, program + extension);
if (Files.exists(fullPath) && Files.isExecutable(fullPath)) {
return true;
}
}
}
return false;
}
static void exec(String... command)
throws Throwable {
var proc = new ProcessBuilder(command).inheritIO().start();
proc.waitFor();
var exit = proc.exitValue();
if (exit != 0) {
throw fail("process failed to exec with code %d.%nproc: %s", exit, emphasize_local(Arrays.toString(command)));
}
}
static void install(Spec spec)
throws Throwable {
out("cargo install %s (%s) %s",
emphasize_global(spec.name),
emphasize_local(spec.bin),
emphasize_local(Arrays.toString(spec.flags)));
var cmd = new String[3 + spec.flags.length];
cmd[0] = "cargo";
cmd[1] = "install";
cmd[2] = spec.name;
System.arraycopy(spec.flags, 0, cmd, 3, spec.flags.length);
exec(cmd);
}
record Spec(String name, String bin, String... flags) {
};
static Spec parse(String line)
throws Throwable {
if (line.startsWith("#"))
{
return null;
}
var by_comma = line.split(";");
if (by_comma.length == 0) {
throw fail("empty line in CSV");
}
if (by_comma.length > 3) {
throw fail("line in CSV should have 1-3 fields%nfound: %s", emphasize_local(line));
}
var name = by_comma[0].strip();
var bin = name;
if (by_comma.length > 1) {
bin = by_comma[1].strip();
}
var flags = new String[] {};
if (by_comma.length == 3) {
flags = by_comma[2].strip().split(" ");
}
return new Spec(name, bin, flags);
}
static void out(String fmt, Object... args) {
out.printf(fmt, args);
out.println();
}
static void dbg(String fmt, Object... args) {
System.err.print("[DBG]: ");
System.err.printf(fmt, args);
System.err.println();
}
static Throwable exit() {
System.exit(0);
// abuse control flow to make compiler realize `exit` will never return
return new Throwable();
}
static String emphasize_global(String message) {
return "\033[4m" + message + "\033[0m";
}
static String emphasize_local(String message) {
return "\033[3m" + message + "\033[0m";
}
static Throwable fail(String message, Object... arguments) {
err.printf(message, arguments);
System.exit(-1);
// abuse control flow to make compiler realize `fail` will never return
return new Throwable();
}
static Throwable fail() {
System.exit(-1);
// abuse control flow to make compiler realize `fail` will never return
return new Throwable();
}
}
new file mode 100644+195 / −0 text lines
let OS = sys host | get name
def main [] {
let install_path = $env.TOOLS | path join bin
let cache_path = make-cache-path 'net.bugabinga.packages'
let packages = open 'packages.nuon'
install-packages $install_path $cache_path $packages
null
}
def make-cache-path [
name: string # application name, for which to generate a stable system location for cache files
] {
let os = sys host | get name
let system_location = if $OS =~ "Windows" {
$env.LOCALAPPDATA
} else if $os =~ "Linux" {
$env | get-or-else XDG_CACHE_HOME ($env.HOME | path join .cache)
} else {
error make {
msg: "unsupported operating system detected! initialising self destruct sequence..."
}
}
let cache_path = $system_location | path join $name
mkdir $cache_path
$cache_path
}
# Gets value of a column, or falls back to given alternative value.
#
def get-or-else [
column: string # name of the column to get its value from
value: any # alternative value to return, in case `get` gets nothing
]: [
record -> any
table -> any
] {
select -i $column | update $column { if ( $in | is-empty ) { $value } else { $in } } | get $column
}
def install-packages [
install_path: path # path where to install packages to
cache_path: path # path where to cache downloaded packed in
packages: list<any> # packages to install
] {
$packages | par-each {
| package |
if ($package | is-installed-in $install_path $cache_path) {
print $"Package ($package.name) is already installed."
} else {
let artifact = download-package $package $cache_path
if $artifact == null {
print $'Package ($package.name) is not available for current operating system. Skipping it!'
return
}
let executable = unpack-executable $package $artifact
install-executable $package $executable $install_path
}
}
}
def download-package [
package: record # package specification
cache: path # cache path for packages
] {
let artifact_path = make-artifact-path $package $cache
if ($artifact_path | path exists) {
return $artifact_path
} else {
mkdir ($artifact_path | path dirname)
let url = make-url? $package
http get --raw --max-time 30sec $url | save --progress --raw $artifact_path
return $artifact_path
}
}
def make-url? [
package: record # package specification
] {
let url_format = match $OS {
"Windows" => { $package.win32_url }
"Linux" => { $package.lnx_url }
_ => { error make { msg: "unknown operating system" } }
}
if $url_format == null {
return null
}
$url_format | str replace --all --regex '\{\s*version\s*\}' $package.version
}
def make-artifact-path [
package: record # package specification
cache: path # cache path for packages
] {
let url = make-url? $package
let artifact_parent_path = [ $cache $package.name ] | path join
let extension = $url | url parse | get path | get-extension
($artifact_parent_path | path join $package.version) + "." + $extension
}
def get-extension []: path -> string {
let path = $in | path parse
if ($path.stem | str ends-with '.tar') {
return ('tar.' + $path.extension)
} else {
return $path.extension
}
}
def unpack-executable [
package: record # package specification
artifact: path # archive or executable
] {
if ($artifact | is-archive ) {
let tmpdir = mktemp --directory --tmpdir 'net.bugabinga.packages.XXXXXX'
run-external ouch '--quiet' decompress '--dir' $tmpdir $artifact
let exe_glob = '(?i)' + $'($tmpdir)/**/*($package.binary)*' | str replace --all '\' '/' | str replace ':' '\:'
let executable = glob --no-dir --no-symlink $exe_glob |
filter { is-executable } |
first
return $executable
} else if ($artifact | is-executable) {
let tmpdir = mktemp --directory --tmpdir 'net.bugabinga.packages.XXXXXX'
cp $artifact $tmpdir
let copy = [ $tmpdir ($artifact | path basename)] | path join
return $copy
} else {
error make {
msg: "unknown package type"
label: {
text: "trying to unpack this artifact failed"
span: (metadata $artifact).span
}
}
}
}
def is-archive []: path -> bool {
let magic_headers = [
0x[FD 37 7A 58 5A 00] # xz
0x[50 4B] # ZIP
0x[1F 8B] # gzip
0x[75 73 74 61 72] # tar
]
$in | is-magic-file $magic_headers
}
def is-executable []: path -> bool {
let magic_headers = [
0x[7F 45 4C 46] # elf
0x[4D 5A] # DOS MZ
]
$in | is-magic-file $magic_headers
}
def is-magic-file [
magic_headers: list<binary> # list of magic headers to check file against
]: path -> bool {
let max_size = $magic_headers | each { length } | math max
let header = open $in | into binary | first $max_size
$magic_headers | any { |magic| $header | bytes starts-with $magic }
}
def install-executable [
package: record # package specification
executable: path # path to an executable to install
installs: path # path to all installed packages
] {
let target = make-target-path $package $installs
mv --interactive --verbose --update $executable $target
}
def is-installed-in [
installs: path # path to all installed packages
cache: path # path to cache of all packages
]: record -> bool {
let package = $in
let is_installed = make-target-path $package $installs | path exists
let is_cached = make-artifact-path $package $cache | path exists
$is_installed and $is_cached
}
def make-target-path [
package: record # package specification
installs: path # path to all installed packages
] {
let target = $installs | path join ($package | get binary | to-executable-name)
return $target
}
def to-executable-name []: string -> string {
[ $in (if $OS =~ "Windows" { '.exe' } else { '' } ) ] | str join
}
new file mode 100644+52 / −0 text lines
[
[name binary version win32_url lnx_url];
[
ouch
ouch
0.5.1
https://github.com/ouch-org/ouch/releases/download/{ version }/ouch-x86_64-pc-windows-msvc.zip
https://github.com/ouch-org/ouch/releases/download/{ version }/ouch-x86_64-unknown-linux-musl.tar.gz
],
[
heatseaker
hs
1.7.2
https://github.com/rschmitt/heatseeker/releases/download/v{ version }/heatseeker-v{ version }-x86_64-pc-windows-msvc.zip
https://github.com/rschmitt/heatseeker/releases/download/v{ version }/heatseeker-v{ version }-x86_64-unknown-linux-musl.tar.gz
],
[
ijq
ijq
1.1.2
https://git.sr.ht/~gpanders/ijq/refs/download/v{ version }/ijq-{ version }-windows-amd64.tar.gz
https://git.sr.ht/~gpanders/ijq/refs/download/v{ version }/ijq-{ version }-linux-amd64.tar.gz
],
[
spoon
spoon
0.0.9
https://github.com/Bios-Marcel/spoon/releases/download/v{ version }/spoon.exe
null
],
[
ttyper
ttyper
1.6.0
https://github.com/max-niederman/ttyper/releases/download/v{ version }/ttyper-x86_64-pc-windows-msvc.zip
https://github.com/max-niederman/ttyper/releases/download/v{ version }/ttyper-x86_64-unknown-linux-musl.tar.gz
],
[
tree-sitter
tree-sitter
0.24.4
https://github.com/tree-sitter/tree-sitter/releases/download/v{ version }/tree-sitter-windows-x64.gz
https://github.com/tree-sitter/tree-sitter/releases/download/v{ version }/tree-sitter-linux-x64.gz
],
[
win32yank
win32yank
0.1.1
https://github.com/equalsraf/win32yank/releases/download/v{ version }/win32yank-x64.zip
null
],
]
+32 / −32 text lines
#!/bin/bashrbwsearch() { SEARCH_ARGS=() RBW_ARGS=() while [[ $# -gt 0 ]]; do case $1 in -f|--field) RBW_ARGS+=("$1" "$2") shift shift ;; -*) RBW_ARGS+=("$1") shift ;; *) SEARCH_ARGS+=("$1") shift ;; esac done rbw unlocked || rbw unlock || return IFS=$'\t' read -r NAME FOLDER < <(rbw list --fields name,folder|sk -q "${SEARCH_ARGS[*]}") if [ -n "$FOLDER" ]; then RBW_ARGS+=("--folder" "$FOLDER") fi rbw get --clipboard "${RBW_ARGS[@]}" "$NAME"}rbwsearch $@#!/bin/bash
rbwsearch() {
SEARCH_ARGS=()
RBW_ARGS=()
while [[ $# -gt 0 ]]; do
case $1 in
-f|--field)
RBW_ARGS+=("$1" "$2")
shift
shift
;;
-*)
RBW_ARGS+=("$1")
shift
;;
*)
SEARCH_ARGS+=("$1")
shift
;;
esac
done
rbw unlocked || rbw unlock || return
IFS=$'\t' read -r NAME FOLDER < <(rbw list --fields name,folder|sk -q "${SEARCH_ARGS[*]}")
if [ -n "$FOLDER" ]; then
RBW_ARGS+=("--folder" "$FOLDER")
fi
rbw get --clipboard "${RBW_ARGS[@]}" "$NAME"
}
rbwsearch $@
deleted file mode 100644+0 / −60 text lines
name;bin;cargo_argsasm-cli-rust; asm-cli-rust; --git https://github.com/cch123/asm-cli-rustbatbkbottom; btmcargo-cachecargo-update;cargo-install-updatecarlcalendar-rs;calendardu-dust; dustdotenv-linterdiskonautevaemplaceeza; eza; --features vendored-openssl,vendored-libgit2fendfd-find;fdgit-delta;deltagitu;gitu; --lockedgitoxide;gixhexylhyperfineinlynejj-cli; jj; --locked --bin jjjustlmslurk-cli; lurklychee;lychee; --locked --no-default-features --features rustls-tls,email-checkmacchinamdbookmdcatmonolithnamesnetscannerneovide;neovide; --git https://github.com/neovide/neovidenu;nu; --lockednu_plugin_audio_hook; nu_plugin_audio_hook; --git https://github.com/FMotalleb/nu_plugin_audio_hook.git --features all-decodersouchpastelpresentermpueue;pueue;--lockedripgrep;rgrbwskim;sksbytesniffnettaplo-cli;taplo; --locked --features lsptealdeer;tldrtokeitopgradetsdlttyperunison-fsmonitorugdbvividwthrryazi-cli;ya; --lockedyazi-fm;yazi; --lockedzoxide+4 / −4 text lines