repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

Merge branch 'trunk' of https://github.com/bugabinga/dotfiles into trunk

2a02f88cfdd57f93a8075aa90f9c0df1f63e6099

Oliver Krylow <o.krylow@isp-insoft.de> ·

unsigned

Browse filesCompare with HEAD

Changed files (13)

+1279 / −1367 text lines

Diff layout

justfile

Modified

+5 / −1 text lines

1616 java bootstripper.java decrypt
1818# install rust user land
19tools:
19crates:
2020 cd tools;java install.java
22# install packages
23packages:
24 cd tools;nu packages.nu
25
2226# typically the initial git remote for the dotfiles repo is https
2327# this command changes the remote to ssh
2428ssh-remote:

nushell/completions/pueue-completions.nu

Modified

+0 / −339 text lines

1module completions {
2
3 def "nu-complete pueue color" [] {
4 [ "auto" "never" "always" ]
5 }
6
7 # Interact with the Pueue daemon
8 export extern pueue [
9 --verbose(-v) # Verbose mode (-v, -vv, -vvv)
10 --color: string@"nu-complete pueue color" # Colorize the output; auto enables color output when connected to a tty
11 --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!
12 --profile(-p): string # The name of the profile that should be loaded from your config file
13 --help(-h) # Print help
14 --version(-V) # Print version
15 ]
17 # 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"'
18 export extern "pueue add" [
19 ...command: string # The command to be added
20 --working-directory(-w): string # Specify current working directory
21 --escape(-e) # Escape any special shell characters (" ", "&", "!", etc.). Beware: This implicitly disables nearly all shell specific syntax ("&&", "&>")
22 --immediate(-i) # Immediately start the task
23 --stashed(-s) # Create the task in Stashed state. Useful to avoid immediate execution if the queue is empty
24 --delay(-d): string # Prevents the task from being enqueued until 'delay' elapses. See "enqueue" for accepted formats
25 --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
26 --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
27 --priority(-o): string # Start this task with a higher priority. The higher the number, the faster it will be processed
28 --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
29 --print-task-id(-p) # Only return the task id instead of a text. This is useful when working with dependencies
30 --help(-h) # Print help
31 ]
33 # Remove tasks from the list. Running or paused tasks need to be killed first
34 export extern "pueue remove" [
35 ...task_ids: string # The task ids to be removed
36 --help(-h) # Print help
37 ]
39 # Switches the queue position of two commands. Only works on queued and stashed commands
40 export extern "pueue switch" [
41 task_id_1: string # The first task id
42 task_id_2: string # The second task id
43 --help(-h) # Print help
44 ]
46 # Stashed tasks won't be automatically started. You have to enqueue them or start them by hand
47 export extern "pueue stash" [
48 ...task_ids: string # Stash these specific tasks
49 --help(-h) # Print help
50 ]
52 # Enqueue stashed tasks. They'll be handled normally afterwards
53 export extern "pueue enqueue" [
54 ...task_ids: string # Enqueue these specific tasks
55 --delay(-d): string # Delay enqueuing these tasks until 'delay' elapses. See DELAY FORMAT below
56 --help(-h) # Print help
57 ]
59 # 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.
60 export extern "pueue start" [
61 ...task_ids: string # Start these specific tasks. Paused tasks will resumed. Queued or Stashed tasks will be force-started
62 --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
63 --all(-a) # Resume all groups! All groups will be set to running and paused tasks will be resumed
64 --children(-c) # Deprecated: this switch no longer has any effect
65 --help(-h) # Print help
66 ]
68 # 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.
69 export extern "pueue restart" [
70 ...task_ids: string # Restart these specific tasks
71 --all-failed(-a) # Restart all failed tasks across all groups. Nice to use in combination with `-i/--in-place`
72 --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
73 --start-immediately(-k) # Immediately start the tasks, no matter how many open slots there are. This will ignore any dependencies tasks may have
74 --stashed(-s) # Set the restarted task to a "Stashed" state. Useful to avoid immediate execution
75 --in-place(-i) # Restart the task by reusing the already existing tasks. This will overwrite any previous logs of the restarted tasks
76 --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
77 --edit(-e) # Edit the tasks' commands before restarting
78 --edit-path(-p) # Edit the tasks' paths before restarting
79 --edit-label(-l) # Edit the tasks' labels before restarting
80 --edit-priority(-o) # Edit the tasks' priorities before restarting
81 --help(-h) # Print help
82 ]
84 # 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.
85 export extern "pueue pause" [
86 ...task_ids: string # Pause these specific tasks. Does not affect the default group, groups or any other tasks
87 --group(-g): string # Pause a specific group
88 --all(-a) # Pause all groups!
89 --wait(-w) # Only pause the specified group and let already running tasks finish by themselves
90 --children(-c) # Deprecated: this switch no longer has any effect
91 --help(-h) # Print help
92 ]
94 # Kill specific running tasks or whole task groups.. Kills all tasks of the default group when no ids or a specific group are provided.
95 export extern "pueue kill" [
96 ...task_ids: string # Kill these specific tasks
97 --group(-g): string # Kill all running tasks in a group. This also pauses the group
98 --all(-a) # Kill all running tasks across ALL groups. This also pauses all groups
99 --children(-c) # Deprecated: this switch no longer has any effect
100 --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
101 --help(-h) # Print help
102 ]
104 # Send something to a task. Useful for sending confirmations such as 'y\n'
105 export extern "pueue send" [
106 task_id: string # The id of the task
107 input: string # The input that should be sent to the process
108 --help(-h) # Print help
109 ]
111 # 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.
112 export extern "pueue edit" [
113 task_id: string # The task's id
114 --command(-c) # Edit the task's command
115 --path(-p) # Edit the task's path
116 --label(-l) # Edit the task's label
117 --priority(-o) # Edit the task's priority
118 --help(-h) # Print help
119 ]
121 # Use this to add or remove groups. By default, this will simply display all known groups.
122 export extern "pueue group" [
123 --json(-j) # Print the list of groups as json
124 --help(-h) # Print help
125 ]
127 # Add a group by name
128 export extern "pueue group add" [
129 name: string
130 --parallel(-p): string # Set the amount of parallel tasks this group can have. Setting this to 0 means an unlimited amount of parallel tasks
131 --help(-h) # Print help
132 ]
134 # Remove a group by name. This will move all tasks in this group to the default group!
135 export extern "pueue group remove" [
136 name: string
137 --help(-h) # Print help
138 ]
140 # Print this message or the help of the given subcommand(s)
141 export extern "pueue group help" [
142 ]
144 # Add a group by name
145 export extern "pueue group help add" [
146 ]
148 # Remove a group by name. This will move all tasks in this group to the default group!
149 export extern "pueue group help remove" [
150 ]
152 # Print this message or the help of the given subcommand(s)
153 export extern "pueue group help help" [
154 ]
156 # Display the current status of all tasks
157 export extern "pueue status" [
158 ...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
159 --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
160 --group(-g): string # Only show tasks of a specific group
161 --help(-h) # Print help (see more with '--help')
162 ]
164 # 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
165 export extern "pueue format-status" [
166 --group(-g): string # Only show tasks of a specific group
167 --help(-h) # Print help
168 ]
170 # 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.
171 export extern "pueue log" [
172 ...task_ids: string # View the task output of these specific tasks
173 --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
174 --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
175 --full(-f) # Show the whole output
176 --help(-h) # Print help
177 ]
179 # Follow the output of a currently running task. This command works like "tail -f"
180 export extern "pueue follow" [
181 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
182 --lines(-l): string # Only print the last X lines of the output before following
183 --help(-h) # Print help
184 ]
186 # 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, ...]
187 export extern "pueue wait" [
188 ...task_ids: string # This allows you to wait for specific tasks to finish
189 --group(-g): string # Wait for all tasks in a specific group
190 --all(-a) # Wait for all tasks across all groups and the default group
191 --quiet(-q) # Don't show any log output while waiting
192 --status(-s): string # Wait for tasks to reach a specific task status
193 --help(-h) # Print help
194 ]
196 # Remove all finished tasks from the list
197 export extern "pueue clean" [
198 --successful-only(-s) # Only clean tasks that finished successfully
199 --group(-g): string # Only clean tasks of a specific group
200 --help(-h) # Print help
201 ]
203 # Kill all tasks, clean up afterwards and reset EVERYTHING!
204 export extern "pueue reset" [
205 --children(-c) # Deprecated: this switch no longer has any effect
206 --force(-f) # Don't ask for any confirmation
207 --help(-h) # Print help
208 ]
210 # Remotely shut down the daemon. Should only be used if the daemon isn't started by a service manager
211 export extern "pueue shutdown" [
212 --help(-h) # Print help
213 ]
215 # 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.
216 export extern "pueue parallel" [
217 parallel_tasks?: string # The amount of allowed parallel tasks. Setting this to 0 means an unlimited amount of parallel tasks
218 --group(-g): string # Set the amount for a specific group
219 --help(-h) # Print help
220 ]
222 def "nu-complete pueue completions shell" [] {
223 [ "bash" "elvish" "fish" "power-shell" "zsh" "nushell" ]
224 }
226 # Generates shell completion files. This can be ignored during normal operations
227 export extern "pueue completions" [
228 shell: string@"nu-complete pueue completions shell" # The target shell
229 output_directory?: string # The output directory to which the file should be written
230 --help(-h) # Print help
231 ]
233 # Print this message or the help of the given subcommand(s)
234 export extern "pueue help" [
235 ]
237 # 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"'
238 export extern "pueue help add" [
239 ]
241 # Remove tasks from the list. Running or paused tasks need to be killed first
242 export extern "pueue help remove" [
243 ]
245 # Switches the queue position of two commands. Only works on queued and stashed commands
246 export extern "pueue help switch" [
247 ]
249 # Stashed tasks won't be automatically started. You have to enqueue them or start them by hand
250 export extern "pueue help stash" [
251 ]
253 # Enqueue stashed tasks. They'll be handled normally afterwards
254 export extern "pueue help enqueue" [
255 ]
257 # 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.
258 export extern "pueue help start" [
259 ]
261 # 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.
262 export extern "pueue help restart" [
263 ]
265 # 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.
266 export extern "pueue help pause" [
267 ]
269 # Kill specific running tasks or whole task groups.. Kills all tasks of the default group when no ids or a specific group are provided.
270 export extern "pueue help kill" [
271 ]
273 # Send something to a task. Useful for sending confirmations such as 'y\n'
274 export extern "pueue help send" [
275 ]
277 # 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.
278 export extern "pueue help edit" [
279 ]
281 # Use this to add or remove groups. By default, this will simply display all known groups.
282 export extern "pueue help group" [
283 ]
285 # Add a group by name
286 export extern "pueue help group add" [
287 ]
289 # Remove a group by name. This will move all tasks in this group to the default group!
290 export extern "pueue help group remove" [
291 ]
293 # Display the current status of all tasks
294 export extern "pueue help status" [
295 ]
297 # 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
298 export extern "pueue help format-status" [
299 ]
301 # 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.
302 export extern "pueue help log" [
303 ]
305 # Follow the output of a currently running task. This command works like "tail -f"
306 export extern "pueue help follow" [
307 ]
309 # 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, ...]
310 export extern "pueue help wait" [
311 ]
313 # Remove all finished tasks from the list
314 export extern "pueue help clean" [
315 ]
317 # Kill all tasks, clean up afterwards and reset EVERYTHING!
318 export extern "pueue help reset" [
319 ]
321 # Remotely shut down the daemon. Should only be used if the daemon isn't started by a service manager
322 export extern "pueue help shutdown" [
323 ]
325 # 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.
326 export extern "pueue help parallel" [
327 ]
329 # Generates shell completion files. This can be ignored during normal operations
330 export extern "pueue help completions" [
331 ]
333 # Print this message or the help of the given subcommand(s)
334 export extern "pueue help help" [
335 ]
337}
339export use completions *

tools/aes.java

Modified

+233 / −233 text lines

1import static java.lang.System.out;
2import static java.nio.file.StandardOpenOption.CREATE_NEW;
3import static java.nio.file.StandardOpenOption.READ;
4import static java.nio.file.StandardOpenOption.WRITE;
5
6import java.nio.file.*;
7import java.nio.charset.*;
8import java.nio.*;
9import java.io.*;
11import java.security.*;
13import javax.crypto.*;
14import javax.crypto.spec.*;
16class aes {
17 enum Command {
18 ENCRYPT, DECRYPT
19 }
21 static Cipher AES_GCM_PKCS5;
22 static byte[] SALT = new byte[] { 116, 104, 101, 32, 109, 111, 111, 110, 32, 105, 115, 32, 104, 105, 100, 100, 101,
23 110, 32, 105, 110, 32, 112, 108, 97, 105, 110, 32, 118, 105, 101, 119 };
24 static SecureRandom RANDOM = new SecureRandom();
25 /*
26 * 12 ist NIST recommendation. supposedly fast and secure enough...
27 */
28 static int GCM_IV_SIZE = 12;
29 /*
30 * AES encrypts 128-blocks internally, so this should be reasonable memory bufer
31 * size.
32 */
33 static int READ_BUFFER_SIZE = 128;
34 /*
35 * Supported sizes for GCM authentication tags seem to be {128, 120, 112, 104,
36 * 96}.
37 * But we do not really care, since we do not use them here.
38 */
39 static int GCM_AUTH_TAG_SIZE = 96;
41 public static void main(String[] arguments) throws Throwable {
42 if (arguments.length == 0) {
43 usage();
44 throw fail();
45 }
47 var input_command = arguments[0];
48 Command command;
49 if ("encrypt".startsWith(input_command)) {
50 command = Command.ENCRYPT;
51 } else if ("decrypt".startsWith(input_command)) {
52 command = Command.DECRYPT;
53 } else {
54 throw fail("unknown command %s given%n", emphasize_global(input_command));
55 }
57 AES_GCM_PKCS5 = Cipher.getInstance("AES/GCM/NoPadding");
59 var console = System.console();
60 /*
61 * If there is no console, this program is most likely part of a pipe.
62 * In such cases a `--password-file` flag is mandatory, because we cannot
63 * interactively ask for the password.
64 */
65 if (console == null) {
66 if (arguments.length != 3 || !"--password-file".equals(arguments[1])) {
67 usage();
68 throw fail(
69 "When running %s non-interactively, the %s flag is required.%nOtherwise there is no way to securely obtain the password.%n",
70 emphasize_local("aes"), emphasize_global("--password-file"));
71 }
72 var password_file = Path.of(arguments[2]);
73 if (!Files.exists(password_file)) {
74 throw fail("the given password file %s does not exist%n", emphasize_local(password_file.toString()));
75 }
76 var password = toChars(Files.readAllBytes(password_file));
77 switch (command) {
78 case ENCRYPT:
79 encrypt(password, System.in, System.out);
80 break;
81 case DECRYPT:
82 decrypt(password, System.in, System.out);
83 break;
84 }
85 } else {
86 if (arguments.length <= 1) {
87 usage();
88 throw fail("not enough arguments given%n");
89 }
90 char[] password;
91 String input;
92 String output;
93 if ("--password-file".equals(arguments[1])) {
94 if (arguments.length != 5) {
95 usage();
96 throw fail("the flag %s requires a path%n", emphasize_local("--password-file"));
97 }
98 var password_file = Path.of(arguments[2]);
99 if (!Files.exists(password_file)) {
100 throw fail("the given password file %s does not exist%n", emphasize_local(password_file.toString()));
101 }
102 password = toChars(Files.readAllBytes(password_file));
103 input = arguments[3];
104 output = arguments[4];
105 } else {
106 if (arguments.length != 3) {
107 usage();
108 throw fail("when encrypting/decrypting a file, an output path is required%n");
109 }
110 password = console.readPassword("[%s]:", emphasize_global("Password"));
111 input = arguments[1];
112 output = arguments[2];
113 }
115 var input_path = Path.of(input);
116 if (!Files.exists(input_path)) {
117 throw fail("the given input path %s does not exist%n", emphasize_global(input_path.toString()));
118 }
119 var output_path = Path.of(output);
120 if (Files.exists(output_path)) {
121 throw fail("the output path %s already exists%n", emphasize_global(output_path.toString()));
122 }
124 try (var input_stream = Files.newInputStream(input_path, READ);
125 var output_stream = Files.newOutputStream(output_path, CREATE_NEW, WRITE);) {
126 switch (command) {
127 case ENCRYPT:
128 encrypt(password, input_stream, output_stream);
129 break;
130 case DECRYPT:
131 decrypt(password, input_stream, output_stream);
132 break;
133 }
134 }
135 }
136 throw exit();
137 }
139 static void encrypt(char[] password, InputStream input, OutputStream output) throws Exception {
140 // FIXME: generate random salt and append it here just like IV
141 // in GCM the IV should be unique per encrypted thingy
142 var initialization_vector = new byte[GCM_IV_SIZE];
143 RANDOM.nextBytes(initialization_vector);
144 // save the IV for the decryption step later. secure? nope. but how else are we
145 // to share IVs between encryption/decryption?
146 output.write(initialization_vector);
147 var secret = toSecretKey(password);
148 var parameter_spec = new GCMParameterSpec(GCM_AUTH_TAG_SIZE, initialization_vector);
150 AES_GCM_PKCS5.init(Cipher.ENCRYPT_MODE, secret, parameter_spec);
151 var read_buffer = new byte[READ_BUFFER_SIZE];
152 var aes_buffer = new byte[READ_BUFFER_SIZE];
153 int read_bytes_count = 0;
154 while ((read_bytes_count = input.read(read_buffer)) != -1) {
155 var aes_bytes_count = AES_GCM_PKCS5.update(read_buffer, 0, read_bytes_count, aes_buffer);
156 output.write(aes_buffer, 0, aes_bytes_count);
157 }
158 output.write(AES_GCM_PKCS5.doFinal());
159 }
161 static void decrypt(char[] password, InputStream input, OutputStream output) throws Exception {
162 // the IV get prepended to the data during encryption
163 var initialization_vector = new byte[GCM_IV_SIZE];
164 input.read(initialization_vector);
165 var parameter_spec = new GCMParameterSpec(GCM_AUTH_TAG_SIZE, initialization_vector);
166 var secret = toSecretKey(password);
168 AES_GCM_PKCS5.init(Cipher.DECRYPT_MODE, secret, parameter_spec);
169 var read_buffer = new byte[READ_BUFFER_SIZE];
170 var aes_buffer = new byte[READ_BUFFER_SIZE];
171 int read_bytes_count = 0;
172 while ((read_bytes_count = input.read(read_buffer)) != -1) {
173 var aes_bytes_count = AES_GCM_PKCS5.update(read_buffer, 0, read_bytes_count, aes_buffer);
174 output.write(aes_buffer, 0, aes_bytes_count);
175 }
176 // the java impl of GCM seems to buffer the whole data in memory and only
177 // releasing it on doFinal. yuck!
178 // there is not much i can do about this other than to wait for JDK patches.
179 // TODO: in the case of AES GCM the final byte block is the authentication tag.
180 // as such it should porbably NOT be written to the output file.
181 // or is this assumption wrong?
182 output.write(AES_GCM_PKCS5.doFinal());
183 // FIXME: when given a wrong password we get a nonsensical error. make this
184 // nicer for human
185 }
187 static SecretKey toSecretKey(char[] password) throws Exception {
188 var factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
189 var spec = new PBEKeySpec(password, SALT, 65536, 256);
190 return new SecretKeySpec(factory.generateSecret(spec).getEncoded(), "AES");
191 }
193 static char[] toChars(byte[] bytes) {
194 var byte_buffer = ByteBuffer.wrap(bytes);
195 var char_buffer = StandardCharsets.UTF_8.decode(byte_buffer);
196 return char_buffer.array();
197 }
199 static void usage() {
200 out.printf("%s encrypts/decrypts data.%n", emphasize_local("Symmetrically "));
201 out.printf("%s: java aes.java <e(ncrypt)|d(ecrypt)> [--password-file <path>] <input path> <output path>%n",
202 emphasize_global("Usage for files"));
203 out.printf("%s: java aes.java <e(ncrypt)|d(ecrypt)> --password-file <path>%n",
204 emphasize_global("Usage for stdin/stdout"));
205 }
207 static Throwable exit() {
208 System.exit(0);
209 // abuse control flow to make compiler realize `exit` will never return
210 return new Throwable();
211 }
213 static String emphasize_global(String message) {
214 return "\033[4m" + message + "\033[0m";
215 }
217 static String emphasize_local(String message) {
218 return "\033[3m" + message + "\033[0m";
219 }
221 static Throwable fail(String message, Object... arguments) {
222 out.printf(message, arguments);
223 System.exit(-1);
224 // abuse control flow to make compiler realize `fail` will never return
225 return new Throwable();
226 }
228 static Throwable fail() {
229 System.exit(-1);
230 // abuse control flow to make compiler realize `fail` will never return
231 return new Throwable();
232 }
233}
1import static java.lang.System.out;
2import static java.nio.file.StandardOpenOption.CREATE_NEW;
3import static java.nio.file.StandardOpenOption.READ;
4import static java.nio.file.StandardOpenOption.WRITE;
5
6import java.nio.file.*;
7import java.nio.charset.*;
8import java.nio.*;
9import java.io.*;
10
11import java.security.*;
12
13import javax.crypto.*;
14import javax.crypto.spec.*;
15
16class aes {
17 enum Command {
18 ENCRYPT, DECRYPT
19 }
20
21 static Cipher AES_GCM_PKCS5;
22 static byte[] SALT = new byte[] { 116, 104, 101, 32, 109, 111, 111, 110, 32, 105, 115, 32, 104, 105, 100, 100, 101,
23 110, 32, 105, 110, 32, 112, 108, 97, 105, 110, 32, 118, 105, 101, 119 };
24 static SecureRandom RANDOM = new SecureRandom();
25 /*
26 * 12 ist NIST recommendation. supposedly fast and secure enough...
27 */
28 static int GCM_IV_SIZE = 12;
29 /*
30 * AES encrypts 128-blocks internally, so this should be reasonable memory bufer
31 * size.
32 */
33 static int READ_BUFFER_SIZE = 128;
34 /*
35 * Supported sizes for GCM authentication tags seem to be {128, 120, 112, 104,
36 * 96}.
37 * But we do not really care, since we do not use them here.
38 */
39 static int GCM_AUTH_TAG_SIZE = 96;
40
41 public static void main(String[] arguments) throws Throwable {
42 if (arguments.length == 0) {
43 usage();
44 throw fail();
45 }
46
47 var input_command = arguments[0];
48 Command command;
49 if ("encrypt".startsWith(input_command)) {
50 command = Command.ENCRYPT;
51 } else if ("decrypt".startsWith(input_command)) {
52 command = Command.DECRYPT;
53 } else {
54 throw fail("unknown command %s given%n", emphasize_global(input_command));
55 }
56
57 AES_GCM_PKCS5 = Cipher.getInstance("AES/GCM/NoPadding");
58
59 var console = System.console();
60 /*
61 * If there is no console, this program is most likely part of a pipe.
62 * In such cases a `--password-file` flag is mandatory, because we cannot
63 * interactively ask for the password.
64 */
65 if (console == null) {
66 if (arguments.length != 3 || !"--password-file".equals(arguments[1])) {
67 usage();
68 throw fail(
69 "When running %s non-interactively, the %s flag is required.%nOtherwise there is no way to securely obtain the password.%n",
70 emphasize_local("aes"), emphasize_global("--password-file"));
71 }
72 var password_file = Path.of(arguments[2]);
73 if (!Files.exists(password_file)) {
74 throw fail("the given password file %s does not exist%n", emphasize_local(password_file.toString()));
75 }
76 var password = toChars(Files.readAllBytes(password_file));
77 switch (command) {
78 case ENCRYPT:
79 encrypt(password, System.in, System.out);
80 break;
81 case DECRYPT:
82 decrypt(password, System.in, System.out);
83 break;
84 }
85 } else {
86 if (arguments.length <= 1) {
87 usage();
88 throw fail("not enough arguments given%n");
89 }
90 char[] password;
91 String input;
92 String output;
93 if ("--password-file".equals(arguments[1])) {
94 if (arguments.length != 5) {
95 usage();
96 throw fail("the flag %s requires a path%n", emphasize_local("--password-file"));
97 }
98 var password_file = Path.of(arguments[2]);
99 if (!Files.exists(password_file)) {
100 throw fail("the given password file %s does not exist%n", emphasize_local(password_file.toString()));
101 }
102 password = toChars(Files.readAllBytes(password_file));
103 input = arguments[3];
104 output = arguments[4];
105 } else {
106 if (arguments.length != 3) {
107 usage();
108 throw fail("when encrypting/decrypting a file, an output path is required%n");
109 }
110 password = console.readPassword("[%s]:", emphasize_global("Password"));
111 input = arguments[1];
112 output = arguments[2];
113 }
114
115 var input_path = Path.of(input);
116 if (!Files.exists(input_path)) {
117 throw fail("the given input path %s does not exist%n", emphasize_global(input_path.toString()));
118 }
119 var output_path = Path.of(output);
120 if (Files.exists(output_path)) {
121 throw fail("the output path %s already exists%n", emphasize_global(output_path.toString()));
122 }
123
124 try (var input_stream = Files.newInputStream(input_path, READ);
125 var output_stream = Files.newOutputStream(output_path, CREATE_NEW, WRITE);) {
126 switch (command) {
127 case ENCRYPT:
128 encrypt(password, input_stream, output_stream);
129 break;
130 case DECRYPT:
131 decrypt(password, input_stream, output_stream);
132 break;
133 }
134 }
135 }
136 throw exit();
137 }
138
139 static void encrypt(char[] password, InputStream input, OutputStream output) throws Exception {
140 // FIXME: generate random salt and append it here just like IV
141 // in GCM the IV should be unique per encrypted thingy
142 var initialization_vector = new byte[GCM_IV_SIZE];
143 RANDOM.nextBytes(initialization_vector);
144 // save the IV for the decryption step later. secure? nope. but how else are we
145 // to share IVs between encryption/decryption?
146 output.write(initialization_vector);
147 var secret = toSecretKey(password);
148 var parameter_spec = new GCMParameterSpec(GCM_AUTH_TAG_SIZE, initialization_vector);
149
150 AES_GCM_PKCS5.init(Cipher.ENCRYPT_MODE, secret, parameter_spec);
151 var read_buffer = new byte[READ_BUFFER_SIZE];
152 var aes_buffer = new byte[READ_BUFFER_SIZE];
153 int read_bytes_count = 0;
154 while ((read_bytes_count = input.read(read_buffer)) != -1) {
155 var aes_bytes_count = AES_GCM_PKCS5.update(read_buffer, 0, read_bytes_count, aes_buffer);
156 output.write(aes_buffer, 0, aes_bytes_count);
157 }
158 output.write(AES_GCM_PKCS5.doFinal());
159 }
160
161 static void decrypt(char[] password, InputStream input, OutputStream output) throws Exception {
162 // the IV get prepended to the data during encryption
163 var initialization_vector = new byte[GCM_IV_SIZE];
164 input.read(initialization_vector);
165 var parameter_spec = new GCMParameterSpec(GCM_AUTH_TAG_SIZE, initialization_vector);
166 var secret = toSecretKey(password);
167
168 AES_GCM_PKCS5.init(Cipher.DECRYPT_MODE, secret, parameter_spec);
169 var read_buffer = new byte[READ_BUFFER_SIZE];
170 var aes_buffer = new byte[READ_BUFFER_SIZE];
171 int read_bytes_count = 0;
172 while ((read_bytes_count = input.read(read_buffer)) != -1) {
173 var aes_bytes_count = AES_GCM_PKCS5.update(read_buffer, 0, read_bytes_count, aes_buffer);
174 output.write(aes_buffer, 0, aes_bytes_count);
175 }
176 // the java impl of GCM seems to buffer the whole data in memory and only
177 // releasing it on doFinal. yuck!
178 // there is not much i can do about this other than to wait for JDK patches.
179 // TODO: in the case of AES GCM the final byte block is the authentication tag.
180 // as such it should porbably NOT be written to the output file.
181 // or is this assumption wrong?
182 output.write(AES_GCM_PKCS5.doFinal());
183 // FIXME: when given a wrong password we get a nonsensical error. make this
184 // nicer for human
185 }
186
187 static SecretKey toSecretKey(char[] password) throws Exception {
188 var factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
189 var spec = new PBEKeySpec(password, SALT, 65536, 256);
190 return new SecretKeySpec(factory.generateSecret(spec).getEncoded(), "AES");
191 }
192
193 static char[] toChars(byte[] bytes) {
194 var byte_buffer = ByteBuffer.wrap(bytes);
195 var char_buffer = StandardCharsets.UTF_8.decode(byte_buffer);
196 return char_buffer.array();
197 }
198
199 static void usage() {
200 out.printf("%s encrypts/decrypts data.%n", emphasize_local("Symmetrically "));
201 out.printf("%s: java aes.java <e(ncrypt)|d(ecrypt)> [--password-file <path>] <input path> <output path>%n",
202 emphasize_global("Usage for files"));
203 out.printf("%s: java aes.java <e(ncrypt)|d(ecrypt)> --password-file <path>%n",
204 emphasize_global("Usage for stdin/stdout"));
205 }
206
207 static Throwable exit() {
208 System.exit(0);
209 // abuse control flow to make compiler realize `exit` will never return
210 return new Throwable();
211 }
212
213 static String emphasize_global(String message) {
214 return "\033[4m" + message + "\033[0m";
215 }
216
217 static String emphasize_local(String message) {
218 return "\033[3m" + message + "\033[0m";
219 }
220
221 static Throwable fail(String message, Object... arguments) {
222 out.printf(message, arguments);
223 System.exit(-1);
224 // abuse control flow to make compiler realize `fail` will never return
225 return new Throwable();
226 }
227
228 static Throwable fail() {
229 System.exit(-1);
230 // abuse control flow to make compiler realize `fail` will never return
231 return new Throwable();
232 }
233}

tools/crates.csv

Added
new file mode 100644

+60 / −0 text lines

1name;bin;cargo_args
2asm-cli-rust; asm-cli-rust; --git https://github.com/cch123/asm-cli-rust
3bat
4bk
5bottom; btm
6cargo-cache
7cargo-update;cargo-install-update
8carl
9calendar-rs;calendar
10du-dust; dust
11dotenv-linter
12diskonaut
13eva
14emplace
15eza; eza; --features vendored-openssl,vendored-libgit2
16fend
17fd-find;fd
18git-delta;delta
19gitu;gitu; --locked
20gitoxide;gix
21hexyl
22hyperfine
23inlyne
24jj-cli; jj; --locked --bin jj
25just
26lms
27lurk-cli; lurk
28lychee;lychee; --locked --no-default-features --features rustls-tls,email-check
29macchina
30mdbook
31mdcat
32monolith
33names
34netscanner
35neovide;neovide; --git https://github.com/neovide/neovide
36nu;nu; --locked
37nu_plugin_audio_hook; nu_plugin_audio_hook; --git https://github.com/FMotalleb/nu_plugin_audio_hook.git --features all-decoders
38ouch
39pastel
40presenterm
41pueue;pueue;--locked
42ripgrep;rg
43rbw
44skim;sk
45sbyte
46sniffnet
47taplo-cli;taplo; --locked --features lsp
48tealdeer;tldr
49tokei
50topgrade
51tsdl
52ttyper
53unison-fsmonitor
54ugdb
55vivid
56wthrr
57yazi-cli;ya; --locked
58yazi-fm;yazi; --locked
59zoxide
60

tools/download_jar.java

Modified

+198 / −198 text lines

1import static java.lang.System.out;
2
3import java.io.*;
4import java.net.*;
5import java.net.http.*;
6import java.net.http.HttpResponse.*;
7import java.nio.file.*;
8import java.util.*;
9import java.util.concurrent.ConcurrentSkipListSet;
11class download_jar {
12 public static void main(final String[] command_line_arguments) {
13 help();
14 var current_working_directory = Paths.get(System.getProperty("user.dir"));
15 var download_directory = current_working_directory.resolve("downloaded_artifacts");
16 var maven_repository = "https://repo.maven.apache.org/maven2";
17 var expected_count_of_arguments = 3;
18 if (contains(command_line_arguments, "-d")) {
19 expected_count_of_arguments = expected_count_of_arguments + 2;
20 try {
21 var given_download_directory = command_line_arguments[index_of(command_line_arguments, "-d") + 1];
22 download_directory = current_working_directory.resolve(given_download_directory);
23 } catch (IndexOutOfBoundsException exception) {
24 out.println("The -d option requires an argument.");
25 usage();
26 fail();
27 }
28 }
29 if (contains(command_line_arguments, "-r")) {
30 expected_count_of_arguments = expected_count_of_arguments + 2;
31 try {
32 var given_maven_repository = command_line_arguments[index_of(command_line_arguments, "-r") + 1];
33 maven_repository = given_maven_repository;
34 } catch (IndexOutOfBoundsException exception) {
35 out.println("The -r option requires an argument.");
36 usage();
37 fail();
38 }
39 }
40 if (command_line_arguments.length != expected_count_of_arguments) {
41 usage();
42 fail();
43 }
44 var maven_coordinates_reversed = new String[3];
45 for (var index = 2; index >= 0; --index) {
46 maven_coordinates_reversed[index] = command_line_arguments[expected_count_of_arguments - index - 1];
47 }
48 var group_id = maven_coordinates_reversed[2];
49 var artifact_id = maven_coordinates_reversed[1];
50 var version = maven_coordinates_reversed[0];
52 if (Files.exists(download_directory) && Files.isRegularFile(download_directory)) {
53 fail("The given download directory path %s already points to a file!%n", download_directory.toString());
54 } else if (!Files.exists(download_directory)) {
55 out.printf("Creating directory at %s%n.", emphasize_global(download_directory.toString()));
56 try {
57 Files.createDirectories(download_directory);
58 } catch (IOException __) {
59 fail("Unable to create directory at %s", emphasize_global(download_directory.toString()));
60 }
61 }
63 var expected_artifact_base_url = guess_maven_artifact_url(maven_repository, group_id, artifact_id, version);
64 var client = HttpClient.newHttpClient();
65 var request = HttpRequest.newBuilder().uri(URI.create(expected_artifact_base_url)).build();
66 var target_directory = download_directory;
67 client.sendAsync(request, BodyHandlers.ofString()).thenApply(HttpResponse::statusCode).thenAccept(status -> {
68 if (status > 299) {
69 fail("Could not find maven artifact at %s.%n", expected_artifact_base_url);
70 } else {
71 download_ressource(client, target_directory,
72 build_ressource_url(expected_artifact_base_url, artifact_id, version, ".jar"));
73 download_ressource(client, target_directory,
74 build_ressource_url(expected_artifact_base_url, artifact_id, version, "-sources.jar"));
75 // FIXME BLOCKER! How do we implement the version clash resolution?
76 // Preferably in a manner that avoids pointless downloads...
77 var processed_cache = new ConcurrentSkipListSet<String>();
78 process_pom(client, processed_cache,
79 build_ressource_url(expected_artifact_base_url, artifact_id, version, ".pom"));
80 }
81 }).join();
83 out.printf("download directory:\t%s%nmaven repository:\t%s%nmaven coordinates:\t%s:%s:%s%n",
84 emphasize_global(download_directory.toString()), emphasize_global(maven_repository), emphasize_global(group_id),
85 emphasize_global(artifact_id), emphasize_global(version));
86 exit();
87 }
89 static Collection<String> process_pom(HttpClient client, Set<String> processed, String pom_url) {
90 if (processed.contains(pom_url))
91 return Collections.emptyList();
92 var request = HttpRequest.newBuilder().uri(URI.create(pom_url)).build();
93 return client.sendAsync(request, BodyHandlers.ofInputStream()).thenApply(input -> {
94 // TODO add pom to list of processed so that a pom only ever gets read once
95 processed.add(pom_url);
96 // TODO traverse path to root of poms and collect managed dependencies
97 // TODO collect declared dependencies from given pom
98 return List.<String>of();
99 }).join();
100 }
102 static void download_ressource(HttpClient client, Path target_directory, String ressource_url) {
103 var request = HttpRequest.newBuilder().uri(URI.create(ressource_url)).build();
104 var ressource_name = ressource_url.substring(ressource_url.lastIndexOf('/') + 1);
105 var target_ressource_path = target_directory.resolve(ressource_name);
106 client.sendAsync(request, BodyHandlers.ofFile(target_ressource_path)).join();
107 }
109 static String build_ressource_url(String base, String artifact_id, String version, String suffix) {
110 var url = new StringBuilder(base);
111 if (!base.endsWith("/"))
112 url.append('/');
113 url.append(artifact_id);
114 url.append('-');
115 url.append(version);
116 url.append(suffix);
117 return url.toString();
118 }
120 static String guess_maven_artifact_url(String base, String group_id, String artifact_id, String version) {
121 var url = new StringBuilder(base);
122 if (!base.endsWith("/"))
123 url.append('/');
124 url.append(group_id.replaceAll("\\.", "\\/"));
125 url.append('/');
126 url.append(artifact_id);
127 url.append('/');
128 url.append(version);
129 url.append('/');
130 return url.toString();
131 }
133 static class Dependency {
134 String artifactId;
135 String groupId;
136 String version;
137 String scope;
138 boolean optional;
139 }
141 static <T> int index_of(T[] array, T item) {
142 var length = array.length;
143 if (length == 0)
144 return -1;
145 for (var index = 0; index < length; ++index) {
146 var element = array[index];
147 if (Objects.equals(element, item))
148 return index;
149 }
150 return -1;
151 }
153 @SafeVarargs
154 static <T> boolean contains(T[] array, T... items) {
155 if (array.length == 0)
156 return false;
157 if (items.length == 0)
158 return false;
159 for (var element : array) {
160 for (var argument : items) {
161 if (element.equals(argument))
162 return true;
163 }
164 }
165 return false;
166 }
168 static void help() {
169 out.printf("Downloads an artifact from a %s repository with its %s.%n", emphasize_local("maven"),
170 emphasize_local("transitive dependencies"));
171 }
173 static void usage() {
174 out.printf("%s: java download_jar.java <group id> <artifact id> <version>%n", emphasize_global("Usage"));
175 }
177 static void exit() {
178 out.printf("%s!%n", emphasize_local("Done"));
179 System.exit(0);
180 }
182 static String emphasize_global(String message) {
183 return "\033[4m" + message + "\033[0m";
184 }
186 static String emphasize_local(String message) {
187 return "\033[3m" + message + "\033[0m";
188 }
190 static void fail(String message, Object... arguments) {
191 out.printf(message, arguments);
192 System.exit(-1);
193 }
195 static void fail() {
196 System.exit(-1);
197 }
198}
1import static java.lang.System.out;
2
3import java.io.*;
4import java.net.*;
5import java.net.http.*;
6import java.net.http.HttpResponse.*;
7import java.nio.file.*;
8import java.util.*;
9import java.util.concurrent.ConcurrentSkipListSet;
10
11class download_jar {
12 public static void main(final String[] command_line_arguments) {
13 help();
14 var current_working_directory = Paths.get(System.getProperty("user.dir"));
15 var download_directory = current_working_directory.resolve("downloaded_artifacts");
16 var maven_repository = "https://repo.maven.apache.org/maven2";
17 var expected_count_of_arguments = 3;
18 if (contains(command_line_arguments, "-d")) {
19 expected_count_of_arguments = expected_count_of_arguments + 2;
20 try {
21 var given_download_directory = command_line_arguments[index_of(command_line_arguments, "-d") + 1];
22 download_directory = current_working_directory.resolve(given_download_directory);
23 } catch (IndexOutOfBoundsException exception) {
24 out.println("The -d option requires an argument.");
25 usage();
26 fail();
27 }
28 }
29 if (contains(command_line_arguments, "-r")) {
30 expected_count_of_arguments = expected_count_of_arguments + 2;
31 try {
32 var given_maven_repository = command_line_arguments[index_of(command_line_arguments, "-r") + 1];
33 maven_repository = given_maven_repository;
34 } catch (IndexOutOfBoundsException exception) {
35 out.println("The -r option requires an argument.");
36 usage();
37 fail();
38 }
39 }
40 if (command_line_arguments.length != expected_count_of_arguments) {
41 usage();
42 fail();
43 }
44 var maven_coordinates_reversed = new String[3];
45 for (var index = 2; index >= 0; --index) {
46 maven_coordinates_reversed[index] = command_line_arguments[expected_count_of_arguments - index - 1];
47 }
48 var group_id = maven_coordinates_reversed[2];
49 var artifact_id = maven_coordinates_reversed[1];
50 var version = maven_coordinates_reversed[0];
51
52 if (Files.exists(download_directory) && Files.isRegularFile(download_directory)) {
53 fail("The given download directory path %s already points to a file!%n", download_directory.toString());
54 } else if (!Files.exists(download_directory)) {
55 out.printf("Creating directory at %s%n.", emphasize_global(download_directory.toString()));
56 try {
57 Files.createDirectories(download_directory);
58 } catch (IOException __) {
59 fail("Unable to create directory at %s", emphasize_global(download_directory.toString()));
60 }
61 }
62
63 var expected_artifact_base_url = guess_maven_artifact_url(maven_repository, group_id, artifact_id, version);
64 var client = HttpClient.newHttpClient();
65 var request = HttpRequest.newBuilder().uri(URI.create(expected_artifact_base_url)).build();
66 var target_directory = download_directory;
67 client.sendAsync(request, BodyHandlers.ofString()).thenApply(HttpResponse::statusCode).thenAccept(status -> {
68 if (status > 299) {
69 fail("Could not find maven artifact at %s.%n", expected_artifact_base_url);
70 } else {
71 download_ressource(client, target_directory,
72 build_ressource_url(expected_artifact_base_url, artifact_id, version, ".jar"));
73 download_ressource(client, target_directory,
74 build_ressource_url(expected_artifact_base_url, artifact_id, version, "-sources.jar"));
75 // FIXME BLOCKER! How do we implement the version clash resolution?
76 // Preferably in a manner that avoids pointless downloads...
77 var processed_cache = new ConcurrentSkipListSet<String>();
78 process_pom(client, processed_cache,
79 build_ressource_url(expected_artifact_base_url, artifact_id, version, ".pom"));
80 }
81 }).join();
82
83 out.printf("download directory:\t%s%nmaven repository:\t%s%nmaven coordinates:\t%s:%s:%s%n",
84 emphasize_global(download_directory.toString()), emphasize_global(maven_repository), emphasize_global(group_id),
85 emphasize_global(artifact_id), emphasize_global(version));
86 exit();
87 }
88
89 static Collection<String> process_pom(HttpClient client, Set<String> processed, String pom_url) {
90 if (processed.contains(pom_url))
91 return Collections.emptyList();
92 var request = HttpRequest.newBuilder().uri(URI.create(pom_url)).build();
93 return client.sendAsync(request, BodyHandlers.ofInputStream()).thenApply(input -> {
94 // TODO add pom to list of processed so that a pom only ever gets read once
95 processed.add(pom_url);
96 // TODO traverse path to root of poms and collect managed dependencies
97 // TODO collect declared dependencies from given pom
98 return List.<String>of();
99 }).join();
100 }
101
102 static void download_ressource(HttpClient client, Path target_directory, String ressource_url) {
103 var request = HttpRequest.newBuilder().uri(URI.create(ressource_url)).build();
104 var ressource_name = ressource_url.substring(ressource_url.lastIndexOf('/') + 1);
105 var target_ressource_path = target_directory.resolve(ressource_name);
106 client.sendAsync(request, BodyHandlers.ofFile(target_ressource_path)).join();
107 }
108
109 static String build_ressource_url(String base, String artifact_id, String version, String suffix) {
110 var url = new StringBuilder(base);
111 if (!base.endsWith("/"))
112 url.append('/');
113 url.append(artifact_id);
114 url.append('-');
115 url.append(version);
116 url.append(suffix);
117 return url.toString();
118 }
119
120 static String guess_maven_artifact_url(String base, String group_id, String artifact_id, String version) {
121 var url = new StringBuilder(base);
122 if (!base.endsWith("/"))
123 url.append('/');
124 url.append(group_id.replaceAll("\\.", "\\/"));
125 url.append('/');
126 url.append(artifact_id);
127 url.append('/');
128 url.append(version);
129 url.append('/');
130 return url.toString();
131 }
132
133 static class Dependency {
134 String artifactId;
135 String groupId;
136 String version;
137 String scope;
138 boolean optional;
139 }
140
141 static <T> int index_of(T[] array, T item) {
142 var length = array.length;
143 if (length == 0)
144 return -1;
145 for (var index = 0; index < length; ++index) {
146 var element = array[index];
147 if (Objects.equals(element, item))
148 return index;
149 }
150 return -1;
151 }
152
153 @SafeVarargs
154 static <T> boolean contains(T[] array, T... items) {
155 if (array.length == 0)
156 return false;
157 if (items.length == 0)
158 return false;
159 for (var element : array) {
160 for (var argument : items) {
161 if (element.equals(argument))
162 return true;
163 }
164 }
165 return false;
166 }
167
168 static void help() {
169 out.printf("Downloads an artifact from a %s repository with its %s.%n", emphasize_local("maven"),
170 emphasize_local("transitive dependencies"));
171 }
172
173 static void usage() {
174 out.printf("%s: java download_jar.java <group id> <artifact id> <version>%n", emphasize_global("Usage"));
175 }
176
177 static void exit() {
178 out.printf("%s!%n", emphasize_local("Done"));
179 System.exit(0);
180 }
181
182 static String emphasize_global(String message) {
183 return "\033[4m" + message + "\033[0m";
184 }
185
186 static String emphasize_local(String message) {
187 return "\033[3m" + message + "\033[0m";
188 }
189
190 static void fail(String message, Object... arguments) {
191 out.printf(message, arguments);
192 System.exit(-1);
193 }
194
195 static void fail() {
196 System.exit(-1);
197 }
198}

tools/git-info

Modified

+337 / −337 text lines

1#!/bin/sh
2#
3# git-info - shows information about a Git repository a la `svn info'
4#
5# How to use:
6# $ git info
7# $ git info ~/src/somewhere/somefile
8# $ git info some/relative/file_or_directory
9# $ git info ~/repos/something.git
10#
11# Copyright (c) 2009-2022 Akinori MUSHA
12#
13# All rights reserved.
14#
15# Redistribution and use in source and binary forms, with or without
16# modification, are permitted provided that the following conditions
17# are met:
18# 1. Redistributions of source code must retain the above copyright
19# notice, this list of conditions and the following disclaimer.
20# 2. Redistributions in binary form must reproduce the above copyright
21# notice, this list of conditions and the following disclaimer in the
22# documentation and/or other materials provided with the distribution.
23#
24# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
25# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
28# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34# SUCH DAMAGE.
35#
37COLOR=
39main () {
40 local opt
41 local OPTS_SPEC="\
42$0 [<options>] [<path>]
44$0 shows information about a Git repository.
45--
46h,help show the help
47color?when show colored output (always|never|auto)
48"
49 eval "$(echo "$OPTS_SPEC" | git rev-parse --parseopt --stuck-long -- "$@" || echo exit $?)"
51 while [ $# -gt 0 ]; do
52 opt="$1"
53 shift
55 case "$opt" in
56 --color)
57 COLOR=always
58 ;;
59 --color\=*)
60 COLOR="${opt#*=}"
61 ;;
62 --)
63 break
64 ;;
65 *)
66 die "Unexpected option: $opt"
67 ;;
68 esac
69 done
71 initialize_colors
73 case "$#" in
74 1)
75 ;;
76 0)
77 if [ -n "$GIT_DIR" ]; then
78 set -- "$GIT_DIR"
79 else
80 set -- .
81 fi
82 ;;
83 *)
84 die "Too many arguments"
85 ;;
86 esac
88 git_info "$1"
89}
91initialize_colors () {
92 if [ -z "$COLOR" ]; then
93 if git config --get-colorbool color.info; then
94 COLOR=always
95 else
96 COLOR=never
97 fi
98 fi
100 case "$COLOR" in
101 always|never)
102 COLOR_BRANCH=$COLOR
103 ;;
104 auto)
105 if git config --get-colorbool color.branch; then
106 COLOR_BRANCH=always
107 else
108 COLOR_BRANCH=never
109 fi
110 ;;
111 *)
112 die "option \`color' expects \"always\", \"auto\", or \"never\""
113 ;;
114 esac
116 if [ "$COLOR" = always ]; then
117 REMOTE_COLOR="$(get_color color.info.remote color.branch.remote red)"
118 LOCAL_COLOR="$(get_color color.info.local color.branch.local green)"
119 PATH_COLOR="$(get_color color.info.path '' 'bold')"
120 REPOSITORY_COLOR="$(get_color color.info.repository '' 'bold')"
121 ID_COLOR="$(get_color color.info.id '' 'yellow')"
122 RESET_COLOR=$(printf "\033[m")
123 else
124 REMOTE_COLOR=
125 LOCAL_COLOR=
126 PATH_COLOR=
127 REPOSITORY_COLOR=
128 ID_COLOR=
129 RESET_COLOR=
130 fi
131}
133get_color () {
134 local key1="$1" key2="$2" fb="$3"
135 local color="$(git config --get-color "$key1" '')"
136 case "$color" in
137 ''|'')
138 git config --get-color "$key2" "$fb"
139 ;;
140 *)
141 printf '%s' "$color"
142 ;;
143 esac
144}
146git_info () {
147 local path="$1" dir relpath root git_dir
149 if [ -d "$path" ]; then
150 dir="$(cd -P "$path" && pwd)" || die "$path: Cannot cd to the directory"
151 case "$path" in
152 *.git)
153 git_dir="$dir"
154 ;;
155 esac
156 elif [ -f "$path" ]; then
157 dir="$(dirname "$path")"
158 dir="$(cd -P "$dir" && pwd)" || die "$dir: Cannot cd to the directory"
159 relpath="$(basename "$path")"
160 else
161 die "$path: No such file or directory"
162 fi
164 if [ -n "$git_dir" ]; then
165 dir=
166 relpath=
167 elif case "$dir" in ?*.git) [ -d "$dir/objects" -a -d "$dir/refs" ] ;; *) false ;; esac; then
168 git_dir="$dir"
169 relpath=
170 else
171 root="$(
172 cd "$dir" || exit 1
173 while [ ! -e .git ]; do
174 [ "$(pwd)" = / ] && exit 1
175 cd ..
176 done
177 pwd
178 )" || die "Not a git repository."
179 git_dir="$root/.git"
180 if [ "$dir" = "$root" ]; then
181 relpath=.
182 elif [ -n "$relpath" ]; then
183 relpath="${dir#"$root/"}/$relpath"
184 else
185 relpath="${dir#"$root/"}"
186 fi
187 fi
189 set -- "$git_dir"
190 if [ -n "$relpath" ]; then
191 set -- "$@" "$relpath"
192 fi
194 do_git_info "$@"
195}
197do_git_info () {
198 local git_dir="$1" relpath="$2" root line field color reset
200 shift
202 echo "Repository Path: $PATH_COLOR$git_dir$RESET_COLOR"
204 if [ $# -gt 0 ]; then
205 root="$(dirname "$git_dir")"
206 if [ "$relpath" = . ]; then
207 echo "Path: $PATH_COLOR$root$RESET_COLOR"
208 else
209 echo "Path: $PATH_COLOR$root/$relpath$RESET_COLOR"
210 fi
211 fi
213 maketemp
215 GIT_DIR="$git_dir" git remote -v > "$TEMPFILE"
216 if [ -s "$TEMPFILE" ]; then
217 echo "Remote Repositories:"
218 sed -e "s/^\([^ ]\{1,\}\)\([ ]\{1,\}\)\([^ ]\{1,\}\)/$REMOTE_COLOR\1$RESET_COLOR\2$REPOSITORY_COLOR\3$RESET_COLOR/" \
219 -e 's/^/ /' \
220 "$TEMPFILE"
221 fi
223 GIT_DIR="$git_dir" git branch -r --color=$COLOR_BRANCH > "$TEMPFILE"
224 if [ -s "$TEMPFILE" ]; then
225 echo "Remote Branches:"
226 sed -e "s/\([ ]\{1,\}->[ ]\{1,\}\)\([^ ]\{1,\}\)/\1$REMOTE_COLOR\2$RESET_COLOR/" \
227 -e 's/^ */ /' "$TEMPFILE"
228 fi
230 GIT_DIR="$git_dir" git branch --color=$COLOR_BRANCH > "$TEMPFILE"
231 if [ -s "$TEMPFILE" ]; then
232 echo "Local Branches:"
233 sed 's/^/ /' "$TEMPFILE"
234 fi
236 echo "Repository Configuration:"
237 GIT_DIR="$git_dir" git config --local --list | sort | {
238 prev_section=
239 prev_subsection=
240 while read line; do
241 case "$line" in
242 (*=*)
243 lhs=$(expr "$line" : '\([^=]\{1,\}\)')
244 rhs=$(expr "$line" : '[^=]\{1,\}=\(.*\)')
245 case "$lhs" in
246 (?*.?*.?*)
247 section=$(expr "$lhs" : '\([^.]\{1,\}\)')
248 subsection=$(expr "$lhs" : '[^.]\{1,\}\.\(.\{1,\}\)\.')
249 key=$(expr "$lhs" : '[^.]\{1,\}\..\{1,\}\.\([^.]\{0,\}\)$')
250 if [ "$section" != "$prev_section" -o "$subsection" != "$prev_subsection" ]; then
251 prev_section=$section
252 prev_subsection=$subsection
253 case "$section" in
254 (remote)
255 subsection=$REMOTE_COLOR$subsection$RESET_COLOR
256 ;;
257 (branch)
258 subsection=$LOCAL_COLOR$subsection$RESET_COLOR
259 esac
260 printf "\t[%s \"%s\"]\n" "$section" "$subsection"
261 fi
262 case "$section" in
263 (remote)
264 if [ "$key" = url ]; then
265 rhs=$REPOSITORY_COLOR$rhs$RESET_COLOR
266 fi
267 ;;
268 (branch)
269 if [ "$key" = remote ]; then
270 rhs=$REMOTE_COLOR$rhs$RESET_COLOR
271 fi
272 esac
273 printf "\t\t%s = %s\n" "$key" "$rhs"
274 ;;
275 (?*.?*)
276 section=$(expr "$lhs" : '\([^.]\{1,\}\)')
277 key=$(expr "$lhs" : '[^.]\{1,\}\.\([^.]\{1,\}\)$')
278 if [ "$section" != "$prev_section" -o -n "$prev_subsection" ]; then
279 prev_section=$section
280 prev_subsection=
281 printf "\t[%s]\n" "$section"
282 fi
283 printf "\t\t$key = $rhs\n"
284 ;;
285 (*)
286 esac
287 esac
288 done
289 }
291 (cd "$root" && GIT_DIR="$git_dir" git log --max-count=1 "$@") | {
292 while read -r field line; do
293 color=
294 reset=
295 case "$field" in
296 commit)
297 field='Commit ID:'
298 color="$ID_COLOR"
299 reset="$RESET_COLOR"
300 ;;
301 *:)
302 ;;
303 '')
304 break
305 ;;
306 esac
307 echo "Last Changed $field $color$line$reset"
308 done
309 cat > "$TEMPFILE"
310 }
311 echo "Last Changed Log:"
312 sed 's/^ / /' "$TEMPFILE"
314 finalize
315}
317die () {
318 [ "$#" -gt 0 ] && echo "$0: $@" >&2
319 finalize
320 exit 1
321}
323TEMPFILE=
325maketemp () {
326 if [ -z "$TEMPFILE" ]; then
327 TEMPFILE="$(mktemp /tmp/git-info.XXXXXX)" || die
328 trap "finalize; exit 130" 1 2 3 15
329 fi
330}
332finalize () {
333 if [ -n "$TEMPFILE" ]; then
334 rm -f "$TEMPFILE"
335 fi
336}
1#!/bin/sh
2#
3# git-info - shows information about a Git repository a la `svn info'
4#
5# How to use:
6# $ git info
7# $ git info ~/src/somewhere/somefile
8# $ git info some/relative/file_or_directory
9# $ git info ~/repos/something.git
10#
11# Copyright (c) 2009-2022 Akinori MUSHA
12#
13# All rights reserved.
14#
15# Redistribution and use in source and binary forms, with or without
16# modification, are permitted provided that the following conditions
17# are met:
18# 1. Redistributions of source code must retain the above copyright
19# notice, this list of conditions and the following disclaimer.
20# 2. Redistributions in binary form must reproduce the above copyright
21# notice, this list of conditions and the following disclaimer in the
22# documentation and/or other materials provided with the distribution.
23#
24# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
25# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
28# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34# SUCH DAMAGE.
35#
36
37COLOR=
38
39main () {
40 local opt
41 local OPTS_SPEC="\
42$0 [<options>] [<path>]
43
44$0 shows information about a Git repository.
45--
46h,help show the help
47color?when show colored output (always|never|auto)
48"
49 eval "$(echo "$OPTS_SPEC" | git rev-parse --parseopt --stuck-long -- "$@" || echo exit $?)"
50
51 while [ $# -gt 0 ]; do
52 opt="$1"
53 shift
54
55 case "$opt" in
56 --color)
57 COLOR=always
58 ;;
59 --color\=*)
60 COLOR="${opt#*=}"
61 ;;
62 --)
63 break
64 ;;
65 *)
66 die "Unexpected option: $opt"
67 ;;
68 esac
69 done
70
71 initialize_colors
72
73 case "$#" in
74 1)
75 ;;
76 0)
77 if [ -n "$GIT_DIR" ]; then
78 set -- "$GIT_DIR"
79 else
80 set -- .
81 fi
82 ;;
83 *)
84 die "Too many arguments"
85 ;;
86 esac
87
88 git_info "$1"
89}
90
91initialize_colors () {
92 if [ -z "$COLOR" ]; then
93 if git config --get-colorbool color.info; then
94 COLOR=always
95 else
96 COLOR=never
97 fi
98 fi
99
100 case "$COLOR" in
101 always|never)
102 COLOR_BRANCH=$COLOR
103 ;;
104 auto)
105 if git config --get-colorbool color.branch; then
106 COLOR_BRANCH=always
107 else
108 COLOR_BRANCH=never
109 fi
110 ;;
111 *)
112 die "option \`color' expects \"always\", \"auto\", or \"never\""
113 ;;
114 esac
115
116 if [ "$COLOR" = always ]; then
117 REMOTE_COLOR="$(get_color color.info.remote color.branch.remote red)"
118 LOCAL_COLOR="$(get_color color.info.local color.branch.local green)"
119 PATH_COLOR="$(get_color color.info.path '' 'bold')"
120 REPOSITORY_COLOR="$(get_color color.info.repository '' 'bold')"
121 ID_COLOR="$(get_color color.info.id '' 'yellow')"
122 RESET_COLOR=$(printf "\033[m")
123 else
124 REMOTE_COLOR=
125 LOCAL_COLOR=
126 PATH_COLOR=
127 REPOSITORY_COLOR=
128 ID_COLOR=
129 RESET_COLOR=
130 fi
131}
132
133get_color () {
134 local key1="$1" key2="$2" fb="$3"
135 local color="$(git config --get-color "$key1" '')"
136 case "$color" in
137 ''|'')
138 git config --get-color "$key2" "$fb"
139 ;;
140 *)
141 printf '%s' "$color"
142 ;;
143 esac
144}
145
146git_info () {
147 local path="$1" dir relpath root git_dir
148
149 if [ -d "$path" ]; then
150 dir="$(cd -P "$path" && pwd)" || die "$path: Cannot cd to the directory"
151 case "$path" in
152 *.git)
153 git_dir="$dir"
154 ;;
155 esac
156 elif [ -f "$path" ]; then
157 dir="$(dirname "$path")"
158 dir="$(cd -P "$dir" && pwd)" || die "$dir: Cannot cd to the directory"
159 relpath="$(basename "$path")"
160 else
161 die "$path: No such file or directory"
162 fi
163
164 if [ -n "$git_dir" ]; then
165 dir=
166 relpath=
167 elif case "$dir" in ?*.git) [ -d "$dir/objects" -a -d "$dir/refs" ] ;; *) false ;; esac; then
168 git_dir="$dir"
169 relpath=
170 else
171 root="$(
172 cd "$dir" || exit 1
173 while [ ! -e .git ]; do
174 [ "$(pwd)" = / ] && exit 1
175 cd ..
176 done
177 pwd
178 )" || die "Not a git repository."
179 git_dir="$root/.git"
180 if [ "$dir" = "$root" ]; then
181 relpath=.
182 elif [ -n "$relpath" ]; then
183 relpath="${dir#"$root/"}/$relpath"
184 else
185 relpath="${dir#"$root/"}"
186 fi
187 fi
188
189 set -- "$git_dir"
190 if [ -n "$relpath" ]; then
191 set -- "$@" "$relpath"
192 fi
193
194 do_git_info "$@"
195}
196
197do_git_info () {
198 local git_dir="$1" relpath="$2" root line field color reset
199
200 shift
201
202 echo "Repository Path: $PATH_COLOR$git_dir$RESET_COLOR"
203
204 if [ $# -gt 0 ]; then
205 root="$(dirname "$git_dir")"
206 if [ "$relpath" = . ]; then
207 echo "Path: $PATH_COLOR$root$RESET_COLOR"
208 else
209 echo "Path: $PATH_COLOR$root/$relpath$RESET_COLOR"
210 fi
211 fi
212
213 maketemp
214
215 GIT_DIR="$git_dir" git remote -v > "$TEMPFILE"
216 if [ -s "$TEMPFILE" ]; then
217 echo "Remote Repositories:"
218 sed -e "s/^\([^ ]\{1,\}\)\([ ]\{1,\}\)\([^ ]\{1,\}\)/$REMOTE_COLOR\1$RESET_COLOR\2$REPOSITORY_COLOR\3$RESET_COLOR/" \
219 -e 's/^/ /' \
220 "$TEMPFILE"
221 fi
222
223 GIT_DIR="$git_dir" git branch -r --color=$COLOR_BRANCH > "$TEMPFILE"
224 if [ -s "$TEMPFILE" ]; then
225 echo "Remote Branches:"
226 sed -e "s/\([ ]\{1,\}->[ ]\{1,\}\)\([^ ]\{1,\}\)/\1$REMOTE_COLOR\2$RESET_COLOR/" \
227 -e 's/^ */ /' "$TEMPFILE"
228 fi
229
230 GIT_DIR="$git_dir" git branch --color=$COLOR_BRANCH > "$TEMPFILE"
231 if [ -s "$TEMPFILE" ]; then
232 echo "Local Branches:"
233 sed 's/^/ /' "$TEMPFILE"
234 fi
235
236 echo "Repository Configuration:"
237 GIT_DIR="$git_dir" git config --local --list | sort | {
238 prev_section=
239 prev_subsection=
240 while read line; do
241 case "$line" in
242 (*=*)
243 lhs=$(expr "$line" : '\([^=]\{1,\}\)')
244 rhs=$(expr "$line" : '[^=]\{1,\}=\(.*\)')
245 case "$lhs" in
246 (?*.?*.?*)
247 section=$(expr "$lhs" : '\([^.]\{1,\}\)')
248 subsection=$(expr "$lhs" : '[^.]\{1,\}\.\(.\{1,\}\)\.')
249 key=$(expr "$lhs" : '[^.]\{1,\}\..\{1,\}\.\([^.]\{0,\}\)$')
250 if [ "$section" != "$prev_section" -o "$subsection" != "$prev_subsection" ]; then
251 prev_section=$section
252 prev_subsection=$subsection
253 case "$section" in
254 (remote)
255 subsection=$REMOTE_COLOR$subsection$RESET_COLOR
256 ;;
257 (branch)
258 subsection=$LOCAL_COLOR$subsection$RESET_COLOR
259 esac
260 printf "\t[%s \"%s\"]\n" "$section" "$subsection"
261 fi
262 case "$section" in
263 (remote)
264 if [ "$key" = url ]; then
265 rhs=$REPOSITORY_COLOR$rhs$RESET_COLOR
266 fi
267 ;;
268 (branch)
269 if [ "$key" = remote ]; then
270 rhs=$REMOTE_COLOR$rhs$RESET_COLOR
271 fi
272 esac
273 printf "\t\t%s = %s\n" "$key" "$rhs"
274 ;;
275 (?*.?*)
276 section=$(expr "$lhs" : '\([^.]\{1,\}\)')
277 key=$(expr "$lhs" : '[^.]\{1,\}\.\([^.]\{1,\}\)$')
278 if [ "$section" != "$prev_section" -o -n "$prev_subsection" ]; then
279 prev_section=$section
280 prev_subsection=
281 printf "\t[%s]\n" "$section"
282 fi
283 printf "\t\t$key = $rhs\n"
284 ;;
285 (*)
286 esac
287 esac
288 done
289 }
290
291 (cd "$root" && GIT_DIR="$git_dir" git log --max-count=1 "$@") | {
292 while read -r field line; do
293 color=
294 reset=
295 case "$field" in
296 commit)
297 field='Commit ID:'
298 color="$ID_COLOR"
299 reset="$RESET_COLOR"
300 ;;
301 *:)
302 ;;
303 '')
304 break
305 ;;
306 esac
307 echo "Last Changed $field $color$line$reset"
308 done
309 cat > "$TEMPFILE"
310 }
311 echo "Last Changed Log:"
312 sed 's/^ / /' "$TEMPFILE"
313
314 finalize
315}
316
317die () {
318 [ "$#" -gt 0 ] && echo "$0: $@" >&2
319 finalize
320 exit 1
321}
322
323TEMPFILE=
324
325maketemp () {
326 if [ -z "$TEMPFILE" ]; then
327 TEMPFILE="$(mktemp /tmp/git-info.XXXXXX)" || die
328 trap "finalize; exit 130" 1 2 3 15
329 fi
330}
331
332finalize () {
333 if [ -n "$TEMPFILE" ]; then
334 rm -f "$TEMPFILE"
335 fi
336}
337
338338main "$@"No final newline

tools/gnome-settings.nu

Modified

+17 / −17 text lines

1#!/usr/bin/env nu
2
3def main [] {
4 const background_settings = [
5 ['key', 'value'];
6 ['picture-uri', 'none']
7 ['color-shading-type', 'solid']
8 ['primary-color', '#131313']
9 ['secondary-color', '#131313']
10 ]
12 $background_settings | each { | setting |
13 run-external gsettings set 'org.gnome.desktop.background' $setting.key $setting.value
14 }
16 null
17}
1#!/usr/bin/env nu
2
3def main [] {
4 const background_settings = [
5 ['key', 'value'];
6 ['picture-uri', 'none']
7 ['color-shading-type', 'solid']
8 ['primary-color', '#131313']
9 ['secondary-color', '#131313']
10 ]
11
12 $background_settings | each { | setting |
13 run-external gsettings set 'org.gnome.desktop.background' $setting.key $setting.value
14 }
15
16 null
17}

tools/install.java

Modified

+146 / −146 text lines

1import static java.lang.System.out;
2import static java.lang.System.err;
3
4import java.nio.file.Files;
5import java.nio.file.Path;
6import java.nio.file.Paths;
7import java.util.Arrays;
8
9final class install {
10 // TODO: platform key in die csv, um os zu unterscheiden.
11 static final String CARGO_PACKAGES_CSV_FILE = "tools.csv";
13 public static void main(String[] __)
14 throws Throwable {
15 exec("cargo", "--version");
17 var csv = Path.of(CARGO_PACKAGES_CSV_FILE);
18 if (!Files.exists(csv)) {
19 throw fail("Expected a CSV file with cargo crates!");
20 }
22 var lines = Files.lines(csv).toArray(String[]::new);
23 for (int index = 1; index < lines.length; ++index) {
24 var line = lines[index];
25 var spec = parse(line);
26 if (spec != null && !which(spec.bin)) {
27 install(spec);
28 }
29 }
30 }
32 static boolean which(String program) {
33 var pathEnv = System.getenv("PATH");
35 if (pathEnv == null || pathEnv.isEmpty()) {
36 return false;
37 }
39 var paths = pathEnv.split(System.getProperty("path.separator"));
40 var extensions = new String[] { "", ".exe", ".bat", ".cmd", ".com" };
42 for (var path : paths) {
43 for (var extension : extensions) {
44 var fullPath = Paths.get(path, program + extension);
45 if (Files.exists(fullPath) && Files.isExecutable(fullPath)) {
46 return true;
47 }
48 }
49 }
51 return false;
52 }
54 static void exec(String... command)
55 throws Throwable {
56 var proc = new ProcessBuilder(command).inheritIO().start();
57 proc.waitFor();
58 var exit = proc.exitValue();
59 if (exit != 0) {
60 throw fail("process failed to exec with code %d.%nproc: %s", exit, emphasize_local(Arrays.toString(command)));
61 }
62 }
64 static void install(Spec spec)
65 throws Throwable {
66 out("cargo install %s (%s) %s",
67 emphasize_global(spec.name),
68 emphasize_local(spec.bin),
69 emphasize_local(Arrays.toString(spec.flags)));
71 var cmd = new String[3 + spec.flags.length];
72 cmd[0] = "cargo";
73 cmd[1] = "install";
74 cmd[2] = spec.name;
76 System.arraycopy(spec.flags, 0, cmd, 3, spec.flags.length);
78 exec(cmd);
79 }
81 record Spec(String name, String bin, String... flags) {
82 };
84 static Spec parse(String line)
85 throws Throwable {
86 if (line.startsWith("#"))
87 {
88 return null;
89 }
90 var by_comma = line.split(";");
91 if (by_comma.length == 0) {
92 throw fail("empty line in CSV");
93 }
94 if (by_comma.length > 3) {
95 throw fail("line in CSV should have 1-3 fields%nfound: %s", emphasize_local(line));
96 }
97 var name = by_comma[0].strip();
98 var bin = name;
99 if (by_comma.length > 1) {
100 bin = by_comma[1].strip();
101 }
102 var flags = new String[] {};
103 if (by_comma.length == 3) {
104 flags = by_comma[2].strip().split(" ");
105 }
106 return new Spec(name, bin, flags);
107 }
109 static void out(String fmt, Object... args) {
110 out.printf(fmt, args);
111 out.println();
112 }
114 static void dbg(String fmt, Object... args) {
115 System.err.print("[DBG]: ");
116 System.err.printf(fmt, args);
117 System.err.println();
118 }
120 static Throwable exit() {
121 System.exit(0);
122 // abuse control flow to make compiler realize `exit` will never return
123 return new Throwable();
124 }
126 static String emphasize_global(String message) {
127 return "\033[4m" + message + "\033[0m";
128 }
130 static String emphasize_local(String message) {
131 return "\033[3m" + message + "\033[0m";
132 }
134 static Throwable fail(String message, Object... arguments) {
135 err.printf(message, arguments);
136 System.exit(-1);
137 // abuse control flow to make compiler realize `fail` will never return
138 return new Throwable();
139 }
141 static Throwable fail() {
142 System.exit(-1);
143 // abuse control flow to make compiler realize `fail` will never return
144 return new Throwable();
145 }
146}
1import static java.lang.System.out;
2import static java.lang.System.err;
3
4import java.nio.file.Files;
5import java.nio.file.Path;
6import java.nio.file.Paths;
7import java.util.Arrays;
8
9final class install {
10 // TODO: platform key in die csv, um os zu unterscheiden.
11 static final String CARGO_PACKAGES_CSV_FILE = "crates.csv";
12
13 public static void main(String[] __)
14 throws Throwable {
15 exec("cargo", "--version");
16
17 var csv = Path.of(CARGO_PACKAGES_CSV_FILE);
18 if (!Files.exists(csv)) {
19 throw fail("Expected a CSV file with cargo crates!");
20 }
21
22 var lines = Files.lines(csv).toArray(String[]::new);
23 for (int index = 1; index < lines.length; ++index) {
24 var line = lines[index];
25 var spec = parse(line);
26 if (spec != null && !which(spec.bin)) {
27 install(spec);
28 }
29 }
30 }
31
32 static boolean which(String program) {
33 var pathEnv = System.getenv("PATH");
34
35 if (pathEnv == null || pathEnv.isEmpty()) {
36 return false;
37 }
38
39 var paths = pathEnv.split(System.getProperty("path.separator"));
40 var extensions = new String[] { "", ".exe", ".bat", ".cmd", ".com" };
41
42 for (var path : paths) {
43 for (var extension : extensions) {
44 var fullPath = Paths.get(path, program + extension);
45 if (Files.exists(fullPath) && Files.isExecutable(fullPath)) {
46 return true;
47 }
48 }
49 }
50
51 return false;
52 }
53
54 static void exec(String... command)
55 throws Throwable {
56 var proc = new ProcessBuilder(command).inheritIO().start();
57 proc.waitFor();
58 var exit = proc.exitValue();
59 if (exit != 0) {
60 throw fail("process failed to exec with code %d.%nproc: %s", exit, emphasize_local(Arrays.toString(command)));
61 }
62 }
63
64 static void install(Spec spec)
65 throws Throwable {
66 out("cargo install %s (%s) %s",
67 emphasize_global(spec.name),
68 emphasize_local(spec.bin),
69 emphasize_local(Arrays.toString(spec.flags)));
70
71 var cmd = new String[3 + spec.flags.length];
72 cmd[0] = "cargo";
73 cmd[1] = "install";
74 cmd[2] = spec.name;
75
76 System.arraycopy(spec.flags, 0, cmd, 3, spec.flags.length);
77
78 exec(cmd);
79 }
80
81 record Spec(String name, String bin, String... flags) {
82 };
83
84 static Spec parse(String line)
85 throws Throwable {
86 if (line.startsWith("#"))
87 {
88 return null;
89 }
90 var by_comma = line.split(";");
91 if (by_comma.length == 0) {
92 throw fail("empty line in CSV");
93 }
94 if (by_comma.length > 3) {
95 throw fail("line in CSV should have 1-3 fields%nfound: %s", emphasize_local(line));
96 }
97 var name = by_comma[0].strip();
98 var bin = name;
99 if (by_comma.length > 1) {
100 bin = by_comma[1].strip();
101 }
102 var flags = new String[] {};
103 if (by_comma.length == 3) {
104 flags = by_comma[2].strip().split(" ");
105 }
106 return new Spec(name, bin, flags);
107 }
108
109 static void out(String fmt, Object... args) {
110 out.printf(fmt, args);
111 out.println();
112 }
113
114 static void dbg(String fmt, Object... args) {
115 System.err.print("[DBG]: ");
116 System.err.printf(fmt, args);
117 System.err.println();
118 }
119
120 static Throwable exit() {
121 System.exit(0);
122 // abuse control flow to make compiler realize `exit` will never return
123 return new Throwable();
124 }
125
126 static String emphasize_global(String message) {
127 return "\033[4m" + message + "\033[0m";
128 }
129
130 static String emphasize_local(String message) {
131 return "\033[3m" + message + "\033[0m";
132 }
133
134 static Throwable fail(String message, Object... arguments) {
135 err.printf(message, arguments);
136 System.exit(-1);
137 // abuse control flow to make compiler realize `fail` will never return
138 return new Throwable();
139 }
140
141 static Throwable fail() {
142 System.exit(-1);
143 // abuse control flow to make compiler realize `fail` will never return
144 return new Throwable();
145 }
146}

tools/packages.nu

Added
new file mode 100644

+195 / −0 text lines

1let OS = sys host | get name
2
3def main [] {
4 let install_path = $env.TOOLS | path join bin
5 let cache_path = make-cache-path 'net.bugabinga.packages'
6 let packages = open 'packages.nuon'
7
8 install-packages $install_path $cache_path $packages
9 null
10}
11
12def make-cache-path [
13 name: string # application name, for which to generate a stable system location for cache files
14] {
15 let os = sys host | get name
16 let system_location = if $OS =~ "Windows" {
17 $env.LOCALAPPDATA
18 } else if $os =~ "Linux" {
19 $env | get-or-else XDG_CACHE_HOME ($env.HOME | path join .cache)
20 } else {
21 error make {
22 msg: "unsupported operating system detected! initialising self destruct sequence..."
23 }
24 }
25 let cache_path = $system_location | path join $name
26 mkdir $cache_path
27 $cache_path
28}
29
30# Gets value of a column, or falls back to given alternative value.
31#
32def get-or-else [
33 column: string # name of the column to get its value from
34 value: any # alternative value to return, in case `get` gets nothing
35]: [
36 record -> any
37 table -> any
38] {
39 select -i $column | update $column { if ( $in | is-empty ) { $value } else { $in } } | get $column
40}
41
42def install-packages [
43 install_path: path # path where to install packages to
44 cache_path: path # path where to cache downloaded packed in
45 packages: list<any> # packages to install
46] {
47 $packages | par-each {
48 | package |
49 if ($package | is-installed-in $install_path $cache_path) {
50 print $"Package ($package.name) is already installed."
51 } else {
52 let artifact = download-package $package $cache_path
53 if $artifact == null {
54 print $'Package ($package.name) is not available for current operating system. Skipping it!'
55 return
56 }
57 let executable = unpack-executable $package $artifact
58 install-executable $package $executable $install_path
59 }
60 }
61}
62
63def download-package [
64 package: record # package specification
65 cache: path # cache path for packages
66] {
67 let artifact_path = make-artifact-path $package $cache
68 if ($artifact_path | path exists) {
69 return $artifact_path
70 } else {
71 mkdir ($artifact_path | path dirname)
72 let url = make-url? $package
73 http get --raw --max-time 30sec $url | save --progress --raw $artifact_path
74 return $artifact_path
75 }
76}
77
78def make-url? [
79 package: record # package specification
80] {
81 let url_format = match $OS {
82 "Windows" => { $package.win32_url }
83 "Linux" => { $package.lnx_url }
84 _ => { error make { msg: "unknown operating system" } }
85 }
86 if $url_format == null {
87 return null
88 }
89 $url_format | str replace --all --regex '\{\s*version\s*\}' $package.version
90}
91
92def make-artifact-path [
93 package: record # package specification
94 cache: path # cache path for packages
95] {
96 let url = make-url? $package
97 let artifact_parent_path = [ $cache $package.name ] | path join
98 let extension = $url | url parse | get path | get-extension
99 ($artifact_parent_path | path join $package.version) + "." + $extension
100}
101
102def get-extension []: path -> string {
103 let path = $in | path parse
104 if ($path.stem | str ends-with '.tar') {
105 return ('tar.' + $path.extension)
106 } else {
107 return $path.extension
108 }
109}
110
111def unpack-executable [
112 package: record # package specification
113 artifact: path # archive or executable
114] {
115 if ($artifact | is-archive ) {
116 let tmpdir = mktemp --directory --tmpdir 'net.bugabinga.packages.XXXXXX'
117 run-external ouch '--quiet' decompress '--dir' $tmpdir $artifact
118 let exe_glob = '(?i)' + $'($tmpdir)/**/*($package.binary)*' | str replace --all '\' '/' | str replace ':' '\:'
119 let executable = glob --no-dir --no-symlink $exe_glob |
120 filter { is-executable } |
121 first
122 return $executable
123
124 } else if ($artifact | is-executable) {
125 let tmpdir = mktemp --directory --tmpdir 'net.bugabinga.packages.XXXXXX'
126 cp $artifact $tmpdir
127 let copy = [ $tmpdir ($artifact | path basename)] | path join
128 return $copy
129 } else {
130 error make {
131 msg: "unknown package type"
132 label: {
133 text: "trying to unpack this artifact failed"
134 span: (metadata $artifact).span
135 }
136 }
137 }
138}
139
140def is-archive []: path -> bool {
141 let magic_headers = [
142 0x[FD 37 7A 58 5A 00] # xz
143 0x[50 4B] # ZIP
144 0x[1F 8B] # gzip
145 0x[75 73 74 61 72] # tar
146 ]
147 $in | is-magic-file $magic_headers
148}
149
150def is-executable []: path -> bool {
151 let magic_headers = [
152 0x[7F 45 4C 46] # elf
153 0x[4D 5A] # DOS MZ
154 ]
155 $in | is-magic-file $magic_headers
156}
157
158def is-magic-file [
159 magic_headers: list<binary> # list of magic headers to check file against
160]: path -> bool {
161 let max_size = $magic_headers | each { length } | math max
162 let header = open $in | into binary | first $max_size
163 $magic_headers | any { |magic| $header | bytes starts-with $magic }
164}
165
166def install-executable [
167 package: record # package specification
168 executable: path # path to an executable to install
169 installs: path # path to all installed packages
170] {
171 let target = make-target-path $package $installs
172 mv --interactive --verbose --update $executable $target
173}
174
175def is-installed-in [
176 installs: path # path to all installed packages
177 cache: path # path to cache of all packages
178]: record -> bool {
179 let package = $in
180 let is_installed = make-target-path $package $installs | path exists
181 let is_cached = make-artifact-path $package $cache | path exists
182 $is_installed and $is_cached
183}
184
185def make-target-path [
186 package: record # package specification
187 installs: path # path to all installed packages
188] {
189 let target = $installs | path join ($package | get binary | to-executable-name)
190 return $target
191}
192
193def to-executable-name []: string -> string {
194 [ $in (if $OS =~ "Windows" { '.exe' } else { '' } ) ] | str join
195}

tools/packages.nuon

Added
new file mode 100644

+52 / −0 text lines

1[
2 [name binary version win32_url lnx_url];
3 [
4 ouch
5 ouch
6 0.5.1
7 https://github.com/ouch-org/ouch/releases/download/{ version }/ouch-x86_64-pc-windows-msvc.zip
8 https://github.com/ouch-org/ouch/releases/download/{ version }/ouch-x86_64-unknown-linux-musl.tar.gz
9 ],
10 [
11 heatseaker
12 hs
13 1.7.2
14 https://github.com/rschmitt/heatseeker/releases/download/v{ version }/heatseeker-v{ version }-x86_64-pc-windows-msvc.zip
15 https://github.com/rschmitt/heatseeker/releases/download/v{ version }/heatseeker-v{ version }-x86_64-unknown-linux-musl.tar.gz
16 ],
17 [
18 ijq
19 ijq
20 1.1.2
21 https://git.sr.ht/~gpanders/ijq/refs/download/v{ version }/ijq-{ version }-windows-amd64.tar.gz
22 https://git.sr.ht/~gpanders/ijq/refs/download/v{ version }/ijq-{ version }-linux-amd64.tar.gz
23 ],
24 [
25 spoon
26 spoon
27 0.0.9
28 https://github.com/Bios-Marcel/spoon/releases/download/v{ version }/spoon.exe
29 null
30 ],
31 [
32 ttyper
33 ttyper
34 1.6.0
35 https://github.com/max-niederman/ttyper/releases/download/v{ version }/ttyper-x86_64-pc-windows-msvc.zip
36 https://github.com/max-niederman/ttyper/releases/download/v{ version }/ttyper-x86_64-unknown-linux-musl.tar.gz
37 ],
38 [
39 tree-sitter
40 tree-sitter
41 0.24.4
42 https://github.com/tree-sitter/tree-sitter/releases/download/v{ version }/tree-sitter-windows-x64.gz
43 https://github.com/tree-sitter/tree-sitter/releases/download/v{ version }/tree-sitter-linux-x64.gz
44 ],
45 [
46 win32yank
47 win32yank
48 0.1.1
49 https://github.com/equalsraf/win32yank/releases/download/v{ version }/win32yank-x64.zip
50 null
51 ],
52]

tools/rbwsearch

Modified

+32 / −32 text lines

1#!/bin/bash
2
3rbwsearch() {
4 SEARCH_ARGS=()
5 RBW_ARGS=()
6
7 while [[ $# -gt 0 ]]; do
8 case $1 in
9 -f|--field)
10 RBW_ARGS+=("$1" "$2")
11 shift
12 shift
13 ;;
14 -*)
15 RBW_ARGS+=("$1")
16 shift
17 ;;
18 *)
19 SEARCH_ARGS+=("$1")
20 shift
21 ;;
22 esac
23 done
24 rbw unlocked || rbw unlock || return
25 IFS=$'\t' read -r NAME FOLDER < <(rbw list --fields name,folder|sk -q "${SEARCH_ARGS[*]}")
26 if [ -n "$FOLDER" ]; then
27 RBW_ARGS+=("--folder" "$FOLDER")
28 fi
29 rbw get --clipboard "${RBW_ARGS[@]}" "$NAME"
30}
32rbwsearch $@
1#!/bin/bash
2
3rbwsearch() {
4 SEARCH_ARGS=()
5 RBW_ARGS=()
6
7 while [[ $# -gt 0 ]]; do
8 case $1 in
9 -f|--field)
10 RBW_ARGS+=("$1" "$2")
11 shift
12 shift
13 ;;
14 -*)
15 RBW_ARGS+=("$1")
16 shift
17 ;;
18 *)
19 SEARCH_ARGS+=("$1")
20 shift
21 ;;
22 esac
23 done
24 rbw unlocked || rbw unlock || return
25 IFS=$'\t' read -r NAME FOLDER < <(rbw list --fields name,folder|sk -q "${SEARCH_ARGS[*]}")
26 if [ -n "$FOLDER" ]; then
27 RBW_ARGS+=("--folder" "$FOLDER")
28 fi
29 rbw get --clipboard "${RBW_ARGS[@]}" "$NAME"
30}
31
32rbwsearch $@

tools/tools.csv

Deleted
deleted file mode 100644

+0 / −60 text lines

1name;bin;cargo_args
2asm-cli-rust; asm-cli-rust; --git https://github.com/cch123/asm-cli-rust
3bat
4bk
5bottom; btm
6cargo-cache
7cargo-update;cargo-install-update
8carl
9calendar-rs;calendar
10du-dust; dust
11dotenv-linter
12diskonaut
13eva
14emplace
15eza; eza; --features vendored-openssl,vendored-libgit2
16fend
17fd-find;fd
18git-delta;delta
19gitu;gitu; --locked
20gitoxide;gix
21hexyl
22hyperfine
23inlyne
24jj-cli; jj; --locked --bin jj
25just
26lms
27lurk-cli; lurk
28lychee;lychee; --locked --no-default-features --features rustls-tls,email-check
29macchina
30mdbook
31mdcat
32monolith
33names
34netscanner
35neovide;neovide; --git https://github.com/neovide/neovide
36nu;nu; --locked
37nu_plugin_audio_hook; nu_plugin_audio_hook; --git https://github.com/FMotalleb/nu_plugin_audio_hook.git --features all-decoders
38ouch
39pastel
40presenterm
41pueue;pueue;--locked
42ripgrep;rg
43rbw
44skim;sk
45sbyte
46sniffnet
47taplo-cli;taplo; --locked --features lsp
48tealdeer;tldr
49tokei
50topgrade
51tsdl
52ttyper
53unison-fsmonitor
54ugdb
55vivid
56wthrr
57yazi-cli;ya; --locked
58yazi-fm;yazi; --locked
59zoxide

tools/wezterm_terminfo.sh

Modified

+4 / −4 text lines

1tempfile=$(mktemp) \
2 && curl -o "$tempfile" https://raw.githubusercontent.com/wez/wezterm/main/termwiz/data/wezterm.terminfo \
3 && tic -x -o ~/.terminfo "$tempfile" \
4 && rm "$tempfile"
1tempfile=$(mktemp) \
2 && curl -o "$tempfile" https://raw.githubusercontent.com/wez/wezterm/main/termwiz/data/wezterm.terminfo \
3 && tic -x -o ~/.terminfo "$tempfile" \
4 && rm "$tempfile"