GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — GitHub - nadvotsky/unistore: A portable project management environment for an extensive collection of diverse solutions.

BranchesTags
Open more actions menu

Latest commit

 

History

13 Commits
13 Commits

Folders and files

NameName
Last commit message
Last commit date
builder
builder
 
 
entry
entry
 
 
package
package
 
 
.gitignore
.gitignore
 
 
LICENSE
LICENSE
 
 
README.md
README.md
 
 
build.py
build.py
 
 

Repository files navigation

The Unistore

This is a repository that provides a portable and customizable environment that incorporates a comprehensive suite of building and miscellaneous tools, offering a streamlined onboarding experience.

Powered by Nushell and Luigi, the Unistore solution can be used in a variety of projects. However, it is especially advantageous for a set of compact projects that require maintenance on a macro scale. The Unistore features a highly adaptable configuration, avoids hardcoded values or imposed semantics, and ensures minimal interference with the existing operating system.

Table of Contents

  • The Unistore
    • Table of Contents
    • Motivation
      • History
      • Actual Stage
    • Summary
    • Supported Platforms
    • Dependencies
      • Basic Runtime
    • Configuration
      • Root Configuration File
        • magic
        • dirs
          • dirs.var
          • dirs.run
          • dirs.binaries
        • lookup
          • lookup.skip
        • constants
          • Quality Value
          • Compression Value
          • Operation Context
          • Mkdirs
          • Override
          • Quiet
          • Check Code
          • Shell
          • FFmpeg AVIF Convert Engine
          • FFmpeg JPEG XL Convert Engine
          • FFmpeg Webp Convert Engine
          • FFmpeg JPEG Convert Engine
          • FFmpeg Opus Convert Engine
          • FFmpeg VP9 Convert Engine
          • FFmpeg AV1 Convert Engine
          • FFmpeg NVENC Convert Engine
          • FFmpeg AVC Convert Engine
          • LibreOffice Convert Engine
          • LibreOffice PDF Convert Engine
          • LibreOffice HTML Convert Engine
          • Tar Convert Engine
          • ZIP Convert Engine
        • run
      • Tag Configuration File
        • magic
        • tags
        • override
      • Variable Configuration File
        • Variable Substitution
        • magic
        • Examples
    • Usage
      • Help Command
      • Enter Command
      • Run Command
      • Find Command
    • Startup Details
      • Startup Routine
      • Target Detection
    • Unistore Python Package
      • Convert Function
      • Convert Engine
      • Logging
      • Code Samples
        • Configure Logging
        • Access Root Configuration File
        • Access Variable Configuration File
        • Access Constants
        • Run External Tool
        • Run Convert Operation
        • Run Convert Operation with Wildcards
        • Run Convert Operation with Overrides
        • Run Convert Operation with Explicit Convert Engine
        • Run Convert Operation with Self-Written Convert Engine
        • Run Convert Operation with Self-Written Convert Engine for Multiple Inputs
      • Command-Line Interface
      • Luigi
        • Running Luigi
        • Convert Engine Wrappers
        • Declare Genuine Luigi Task
        • Declare Task with Unistore Stub
        • Run Convert Operation with Luigi
        • Run Convert Operation from SubTask
        • Run Convert Operation with Convert Function
    • Building
      • Requirements
      • Instruction
      • Customization
    • Common Questions
    • Credits
    • License

Motivation

History

Well, initially, the plan around this solution was much broader. Unfortunately, some ideas were left behind due to implementation complexity, questionable coverage of everything and nothing at the same time, and an ambitious attempt to reinvent the wheel.

For example, lightweight portability is the highest priority. But virtualization is also awesome! To solve this, vagrant might be used, since it covers many of the virtualization solutions:

  • Docker (GNU/Linux, Windows, macOS)
  • VirtualBox
  • VMWare
  • Hyper-V
  • QEMU (it can be portable)

So originally, the Unistore was intended to be built across Ruby programming language. This also means that RAKE could have been integrated.

However, this project raises more questions than it answers. For example, even if some, let's say, devenv.toml is designed to easily launch virtualized/baremetal environment:

  • What is the way a provisioning could be done? Is it some additional tool like Packer or Ansible that brings more dependencies?
  • What about artifacts downloading, is it a central repository or OS package manager (only Windows has scoop, choco, winget)?
  • What kind of solution is viable to create an image layering. Again, it would make a lot of things to be taken care of (Docker images are definitely not the same as qcow files).
  • What kind of design is appropriate for managing running instances. It should not be only success and error. Many things to think about RPCs, signals, return codes, subscriptions.
  • Many other minor problems:
    • Additional arguments passed to RAKE would require manual handling, therefore a lot of modifications with typechecking.
    • Portable/daemonless approach might be very problematic for some runtimes.
    • User customization of IDEs, shell, and other tools is troublesome; more abstractions are required.
    • Graphics forwarding brings a lot of complexities; please refer to the rdp in containers, x11docker.
    • Secrets/dotenv managing, most notably Vault.
    • Not even mentioning any optimizations or clarification for image resizing, caching, GPUs passthrough etc.
  • What is the way to not turn this into something that is extremely tied to a particular environment and is nothing but a hardcoded thing that cannot be used outside of context?

Of course, that does not mean that the whole idea is dead. But again, there are a lot of things to think about. And also, the whole idea of building around a single programming language is a bit of naive, because almost every component of such requires appropriate modification.

Actual Stage

So in this way, some shrinking has been done in the intention of the Unistore. However, even this approach encountered differing perspectives, including code-only, configuration-only, and mixed solutions:

  • Single binary Deno JavaScript runtime with dynamic dependencies resolution and a lot of task runners like drake, dunner.
  • Python with a series of beautiful task runners: Invoke, doit.
  • YAML task runners: upcmd, Task, taskctl, pypyr.
  • Combination of both code and configuration: RKD, Snakemake

A considerable effort has been made to get rid of any office software suite, because none of these formats is portable nor compatible even with their own versions! Several promising alternatives have been found:

  • asciidoctor with its asciidoctor-pdf converter.
  • DocBook.
  • Self-written solution based on any HTML/XML template engine:
    • This would give a possibility to effectively parse and create an intermediate docx/odt/md.
    • Instead of creating own pdf converter, one may use pandoc, OpenOffice Document Builder, and others.

However, due to the complexity of the migration and lack of time, simple variable injection is implemented instead.

Nevertheless, the current state of the project serves its intended purpose effectively. In conclusion, the journey of conceptualizing and refining the Unistore has been fraught with challenges. But its current form offers a simple portable solution with easy startup, adaptability, simplicity, and basic multimedia/docs/metadata/archives manipulation, while still being open for further customization.

Summary

A simple, cross-platform, portable, yet extensible solution.

Consists of:

  • The Unistore entry binary:
    • Written in Go. Source code is available at the ./entry.
    • Self-extracting single binary with concurrent Zstandard unpacking. Refer to the Startup Details for more info
    • Easy startup drop-in to Nushell without the PATH variable manipulations with the Enter Command.
    • Fast concurrent tag search against the Tag Configuration Files with the Find Command.
  • Nushell shell:
    • High-level scripting language where everything is data, with powerful constructions and functions.
    • Built-in support for syntax highlighting, command history, and useful hotkeys.
    • Scripting that is stored in the run field of the Root Configuration File and can be invoked via the Run Command.
  • The Unistore package:
    • Written in Python. Source code is available at the ./package.
    • Simple module with a single entry function, the Convert Function.
    • Can be invoked via CLI, any Python code, or Luigi task.
    • Customizable defaults (constants) in the Constants field of the Root Configuration File.
    • Typechecking with pydantic.
    • Trouble-free extensibility. For instance, refer to the Run Convert Operation with Self-Written Convert Engine.
    • Build-in Convert Engines for files, documents, and media.
  • LibreOffice
  • ffmpeg
  • exiftool
  • qpdf

Supported Platforms

There are actually two different kinds of releases: generic and targeted.

The first one is generic. It is a small binary that includes only the Unistore entry and does not ship any of the portable binaries such as libreoffice or ffmpeg. This kind of release is limited only by GOOS and GOARCH. That means it can be compiled to any in this roster:

  • Arch: i386, x86_64, aarch64, and more.
  • OS: android, darwin, freebsd, solaris, illumos, and others.

The second one is targeted. It is a relatively big (300–500Mb) binary that includes a compressed bundle with tools for necessities. This kind of release is exclusively available for x86_64 architecture and only for nt (Microsoft Windows) and linux operating systems.

Dependencies

Basic Runtime

It is challenging to determine what exactly a basic runtime is. To just run unistore --help, only a basic operating system is required. However, listed here dependencies allow building most of the projects.

For Microsoft Windows operating system family:

  • Windows 8 and newer (because of python).
  • UCRT (already shipped with Windows 10).

For a GNU/Linux distribution with glibc implementation:

  • libfuse (because of .AppImage).
  • libcrypto.so.1.1 (because of qpdf; that is, libxcrypt-compat for Arch and libcrypt1 for apt and so on).

For a GNU/Linux distribution with musl implementation/other supported OSs like FreeBSD:

  • ffmpeg
  • python >= 3.12 (because of PEP695)
  • libreoffice
  • exiftool
  • qpdf

Configuration

The Unistore uses a TOML file format for configuration files. There are three different kinds of configuration files:

  1. Root configuration file with magic filed set to !UNISTORE-ROOT-ECF8.
  2. Tag configuration file with magic field set to !UNISTORE-TAG-ECF8.
  3. Variable configuration file with magic field set to !UNISTORE-VAR-ECF8.

Configuration files can have arbitrary name, but the extension must be set to .toml.

Root Configuration File

The Root Configuration File is a logical marker that points to the root of the Unistore. It declares all the required properties that need to be resolved during the startup of the Unistore. This file is responsible for configuring the following:

  • Basic hierarchy for directories that would be used for portable binaries storage and platform independent files (dirs.var and dirs.run).
  • Binary lookup rules for portable storage according to the current system (dirs.binaries).
  • Search rules for the Tag Configuration File and the Variable Configuration File (lookup).
  • Constants for all kinds of operations invoked from build scripts, the command-line interface, or regular scripts (constants).
  • List of scripts that can be executed in the context of the current Unistore using a Nushell (run).

In the process of rebuilding the internal directory structure of the Unistore, the Root Configuration File is located during each run. This process aims to minimize the use of absolute paths and hardcoded values. It is essential to exclusively manipulate files that pertain to the root directory of the Unistore.

For instance, having /data/myunistore/unistore.toml is reasonable for the project located in /data/myunistore/usr/branch/local/project.

Conversely, having /home/unistore.toml is unacceptable for the project situated in /data/myunistore/usr/branch/local/project.

Proceed to the unistore.toml for a complete example.

magic

This field has a special meaning and indicates the revision of the Unistore. Must be set to !UNISTORE-ROOT-ECF8.

Examples:

magic = "!UNISTORE-ROOT-ECF8"

dirs

This field configures directories that are being used by the Unistore.

dirs.var

This field points to the variable data directory. It contains all portable tools that have been extracted during the startup of the Unistore entry.

This directory is never utilized "as is" and acts as the parent directory for each of the subdirectories formed using the target identifier.

The content of these directories is created automatically, refer to the Startup Details section for more information. Use of this directory is coercive, but its content is not.

If portable tools inside the bundle are not required (e.g., because of the globally installed ones), subdirectories under the dirs.var/{target} can be safety removed. This will cause binary resolution to fall to the system binaries.

Modifying the content of these directories is also possible, but not encouraged, since it does not reflect these changes to the internal Unistore entry bundle and may be misleading, especially when using multiple targets.

Both of these practices can be a source of some version mismatch problems.

For instance, across various releases, LibreOffice adopted different methods for passing parameters via the command-line interface:

  • --convert-to pdf:"writer_pdf_Export:SelectPdfVersion=1"
  • --convert-to pdf:writer_pdf_Export:{"SelectPdfVersion":{"type":"long","value":"1"}}

Examples:

[dirs]
var = "./var"
dirs.run

This field points to the runtime variable data. It contains files that are target independent and specific to this Unistore only. For example, this directory may include: git repositories, indexed caches, configuration files, and others.

Examples:

[dirs]
run = "./run"
dirs.binaries

This field points to the table of binary lookup rules.

When using dirs.var that may contain portable tools, some inconsistencies may occur during binary resolution. Suppose that, when looking for python, the following may happen:

  • For nt-x86_64, unistore-root/{dirs.var}/python/python.exe is needed.
  • For linux-glibc-x86_64, unistore-root/{dirs.var}/python/bin/python3 is needed.

To solve this, this field contains a list of the target-to-binary mappings. A binary resolution for {binary} will only fail if all of these searches have failed:

  • dirs.var/target/{mapping} if there is a mapping in dirs.binaries
  • dirs.var/target/{binary}/{binary}
  • {binary} in the $PATH environment variable

Examples:

[data.binaries.libreoffice]
nt-x86_64 = "./libreoffice/App/libreoffice/program/soffice.exe"
linux-glibc-x86_64 = "./libreoffice/libreoffice.AppImage"

lookup

This field configures lookup rules for searching the Variable Configuration Files and the Tag Configuration Files.

The need for this mechanism arises because the discovery of configuration files is performed using recursive search. This eliminates the requirement for a strict directory hierarchy but still has to be configurable in some way to reflect the specific Unistore preferences.

lookup.skip

This field points to the list of directory patterns to exclude from the configuration files lookup. It supports wildcards (*), and the POSIX path separator (/) on all platforms.

For instance, for the given Unistore:

data/
└── unistore/
    ├── unistore.toml
    ├── etc/
    │   └── varfile.toml
    └── projects/
        ├── my-project/
        │   ├── etc/
        │   │   ├── varfile.toml
        │   │   └── tagfile.toml
        │   └── src
        └── another-project

Having a lookup process started at data/unistore/projects/my-project, it is probably expected to process only the following files:

  • data/unistore/projects/my-project/etc/varfile.toml
  • data/unistore/projects/my-project/etc/tagfile.toml
  • data/unistore/etc/varfile.toml

Nevertheless, the lookup process is unaware of this preference and, by default, follows these steps:

  • One-level depth: data/unistore/projects/my-project
    • etc
    • src
  • One-level depth: data/unistore/projects
    • another-project
    • excluding my-project as it has already been processed
  • One-level depth: data/unistore
    • etc
    • excluding projects as it has already been processed
  • The process stops once unistore.toml is found (which points to the root of this Unistore).

However, this may lead to undesired results, as data/unistore/projects/another-project is included while working from my-project! To resolve this, lookup.skip may be set to ["./projects"]. It would not affect the current project my-project, but will exclude the directories in the projects directory.

Examples:

[lookup]
skip = [
    "./projects"
]

constants

This field defines strongly specified constants associated with the Unistore environment. It is important to note that these constants influence only the defaults of corresponding configuration options, yet they can still be readily overwritten by the end user if necessary.

The values feature relaxed typing. For example:

  • Any of "1", "YES", true, 1 is acceptable as a boolean.
  • Any of "123", 123 is acceptable as an integer.
  • And so forth. See also the Conversion Table.

Note that specific validation processes are not executed until the values are actually utilized.

Most of the values are mandatory. However, some of them can be omitted. In this case, due to the nature of TOML, this means that this value represents the absence of the value (i.e., none/null/nil). To distinguish whether a particular constant is obligatory, refer to the corresponding documentation section.

A lack of constant and respective override practically means that the option is unset. For instance, refusing to set the ffmpeg-avif-convert-engine-tune for the ffmpeg avif conversion engine would mean that this option will not be passed to the ffmpeg binary at all.

Quality Value

The quality value can be set for multiple constants and goes through the same validation process. For brevity, it is described only once.

quality must be one of the following options:

  • default
    • This is the default value applicable for most cases.
  • best
    • This option provides the best possible quality, but it may result in inefficient choices (e.g., lossless AVIF mode may not be an optimal idea to follow).
  • medium
    • This sets the quality to a medium level.
  • bad
    • This selects a bad quality option, which may still be suitable for specific cases (e.g., sketch images).
  • 0-100
    • This allows specifying the quality as a percentage from 0 to 100. It enables the specification of more sophisticated values (e.g., 0 is likely the worst possible option, while bad is just bad).
Compression Value

The compression value is expected to be understood in the same context across multiple constants. Hence, it is documented herein just once.

compression must be one of the following options:

  • default
    • This is the default value that tends to follow the time–memory trade-off.
  • store
    • This achieves the lowest possible computation complexity, with no compression at all if possible.
  • medium
    • This options sets a reasonable compromise between processing time and compaction.
  • extreme
    • This options seeks for the best possible compression ratio at all costs.
  • 0-100
    • This option allows adjusting the compression as a percentage from 0 to 100.
Operation Context

Some constants are expected to be set in specific context. For instance, some constant may be restricted to be applied to the command-line interface invocations only. There are the following contexts available:

  • operations-convert prefix
    • A direct call of the unistore.operations.convert function.
  • operations-run
    • A direct call of the unistore.operations.run function. It does not affect internal binaries.
  • cli prefix
    • A call from the command-line interface.
  • luigi-convert
    • A call from the unistore.luigi.convert task, including inherited tasks.
  • luigi-run
    • A call from the unistore.luigi.luigi_run task. It does not affect internal binaries.
Mkdirs

These constants control the output directory creation policy.

  • constants.operations-convert-mkdirs
  • constants.cli-mkdirs
  • constants.luigi-convert-mkdirs
    • Description: Set whether the output directory must be created recursively.
    • Required: Yes.
    • Note: Refer to the Operation Context.
Override

These constants control whether the existing output must be replaced.

  • constants.operations-convert-override
  • cli-override
  • luigi-convert-override
    • Description: Set whether the output must be replaced.
      • yes: Always override output.
      • no: Never override output.
      • uptodate: Override the output file only if the modification date of the input file is newer than that of the output file.
    • Required: Yes.
    • Note: Refer to the Operation Context.
Quiet

These constants control verbose output.

  • operations-run-quiet
  • luigi-run-quiet
    • Description: Do not print verbose output.
    • Required: Yes.
    • Note: Refer to the Operation Context.
  • ffmpeg-convert-engine-quiet
    • Description: Do not print output of ffmpeg-based convert engines.
    • Required: Yes.
  • libreoffice-convert-engine-quiet
    • Description: Do not print output of libreoffice-based convert engines.
    • Required: Yes.
  • tar-convert-engine-quiet
  • zip-convert-engine-quiet
    • Description: Do not print each added file to the archive (similar to tar v).
    • Required: Yes.
Check Code

These constants control error code assertion for external binaries run by the user.

  • operations-run-check-code
  • luigi-run-check-code
    • Description: Whether to check the output code.
    • Required: Yes.
    • Note: Refer to the Operation Context.
Shell

These constants control whether external binaries should be executed directly or via the system shell. For more information, refer to the subprocess documentation.

  • operations-run-shell
  • luigi-run-shell
    • Description: Whether to use the system shell or create a new process directly otherwise.
    • Required: Yes.
    • Note: Refer to the Operation Context.
FFmpeg AVIF Convert Engine

These constants control the FFmpeg-based AVIF convert engine.

  • ffmpeg-avif-convert-engine-quality
    • Description: Set the output quality.
    • Required: Yes.
    • Note: Refer to the Quality Value.
  • ffmpeg-avif-convert-engine-compression
    • Description: Set the output compression.
    • Required: Yes.
    • Note: Refer to the Compression Value.
  • ffmpeg-avif-convert-engine-tune
    • Description: Set the distortion metric.
    • Required: No.
    • Note: Refer to the libaom-av1 tune option.
  • ffmpeg-avif-convert-engine-row-mt
    • Description: Whether to use the row-based multi-threading.
    • Required: No.
    • Note: Refer to the libaom-av1 row-mt option.
  • ffmpeg-avif-convert-engine-tiles
    • Description: Set the number of tiles.
    • Required: No.
    • Note: Refer to the libaom-av1 tiles option.
  • ffmpeg-avif-convert-engine-tiles
    • Description: Set the additional libaom options.
    • Required: No.
    • Note: Refer to the libaom-av1 aom-params option.
FFmpeg JPEG XL Convert Engine

These constants control the FFmpeg-based JPEG XL convert engine.

  • ffmpeg-jpeg-xl-convert-engine-quality
    • Description: Set the output quality.
    • Required: Yes.
    • Note: Refer to the Quality Value.
  • ffmpeg-jpeg-xl-convert-engine-compression
    • Description: Set the output compression.
    • Required: Yes.
    • Note: Refer to the Compression Value.
FFmpeg Webp Convert Engine

These constants control the FFmpeg-based Webp convert engine.

  • ffmpeg-webp-convert-engine-quality
    • Description: Set the output quality.
    • Required: Yes.
    • Note: Refer to the Quality Value.
  • ffmpeg-webp-convert-engine-compression
    • Description: Set the output compression.
    • Required: Yes.
    • Note: Refer to the Compression Value.
  • ffmpeg-webp-convert-engine-preset
    • Description: Set the configuration preset based on the general type of the image.
    • Required: No.
    • Note: Refer to the libwebp preset option.
FFmpeg JPEG Convert Engine

These constants control the FFmpeg-based JPEG convert engine.

  • ffmpeg-jpeg-convert-engine-quality
    • Description: Set the output quality.
    • Required: Yes.
    • Note: Refer to the Quality Value.
  • ffmpeg-jpeg-convert-engine-compression
    • Description: Set the output compression.
    • Required: Yes.
    • Note: Refer to the Compression Value.
FFmpeg Opus Convert Engine

These constants control the ffmpeg-based Opus convert engine.

  • ffmpeg-opus-convert-engine-quality
    • Description: Set the output quality.
    • Required: Yes.
    • Note: Refer to the Quality Value.
FFmpeg VP9 Convert Engine

These constants control the FFmpeg-based VP9 convert engine.

  • ffmpeg-vp9-convert-engine-quality
    • Description: Set the output quality.
    • Required: Yes.
    • Note: Refer to the Quality Value.
  • ffmpeg-vp9-convert-engine-compression
    • Description: Set the output compression.
    • Required: Yes.
    • Note: Refer to the Compression Value.
  • ffmpeg-vp9-convert-engine-row-mt
    • Description: Whether to use the row-based multi-threading.
    • Required: No.
    • Note: Refer to the libvpx row-mt option.
  • ffmpeg-vp9-convert-engine-tune
    • Description: Set the distortion metric.
    • Required: No.
    • Note: Refer to the libvpx tune option.
  • ffmpeg-vp9-convert-engine-deadline
    • Description: Set the deadline.
    • Required: No.
    • Note: Refer to the VP9 Encoding Guide.
FFmpeg AV1 Convert Engine

These constants control the ffmpeg-based AV1 convert engine.

  • ffmpeg-av1-convert-engine-quality
  • ffmpeg-av1-convert-engine-compression
  • ffmpeg-av1-convert-engine-row-mt
  • ffmpeg-av1-convert-engine-tune
  • ffmpeg-av1-convert-engine-tiles
  • ffmpeg-av1-convert-engine-row-aom-params

Please refer to the description of the FFmpeg AVIF Convert Engine. Since they are based on the same library libaom-av1, there is no difference between them except for the ffmpeg-av1 and ffmpeg-avif prefixes.

FFmpeg NVENC Convert Engine

These constants control the FFmpeg-based NVENC convert engine.

  • ffmpeg-nvenc-convert-engine-quality
    • Description: Set the output quality.
    • Required: Yes.
    • Note: Refer to the Quality Value.
  • ffmpeg-nvenc-convert-engine-compression
    • Description: Set the output compression.
    • Required: Yes.
    • Note: Refer to the Compression Value.
  • ffmpeg-nvenc-convert-engine-hevc
    • Description: Whether to use High Efficiency Video Coding or Advanced Video Coding.
    • Required: Yes.
    • Note: Refer to the HWAccelIntro.
  • ffmpeg-nvenc-convert-engine-level
    • Description: Set the level, a set of constraints for a bitstream.
    • Required: No.
    • Note: Refer to the HEVC tiers and levels and AVC levels.
  • ffmpeg-nvenc-convert-engine-gpu
    • Description: Set a particular GPU on a multi-GPU system.
    • Required: No.
    • Note: Index is zero-based.
  • ffmpeg-nvenc-convert-engine-tune
    • Description: Set the encoding tuning.
    • Required: No.
    • Note: Run ffmpeg -h encoder=h264_nvenc and ffmpeg -h encoder=hevc_nvenc for more info.
FFmpeg AVC Convert Engine

These constants control the FFmpeg-based AVC convert engine.

  • ffmpeg-avc-convert-engine-quality
    • Description: Set the output quality.
    • Required: Yes.
    • Note: Refer to the Quality Value.
  • ffmpeg-avc-convert-engine-compression
    • Description: Set the output compression.
    • Required: Yes.
    • Note: Refer to the Compression Value.
  • ffmpeg-avc-convert-engine-tune
    • Description: Set the tuning.
    • Required: Yes.
    • Note: Refer to the H.264 Video Encoding Guide.
LibreOffice Convert Engine

These constants control generic options of the LibreOffice-based convert engine.

  • libreoffice-convert-engine-aliases
    • Description: Set the table of aliases for injected variables.
    • Required: Yes.
    • Note: Supports the Variable Substitution.
  • libreoffice-convert-engine-open-tag
    • Description: Set the opening tag for the variable injection expression.
    • Required: Yes.
  • libreoffice-convert-engine-close-tag
    • Description: Set the closing tag for the variable injection expression.
    • Required: Yes.
LibreOffice PDF Convert Engine

These constants control the LibreOffice-based PDF convert engine.

  • libreoffice-pdf-convert-engine-quality
    • Description: Set the output quality of images, or entire document when the libreoffice-pdf-convert-engine-rasterize is set.
    • Required: Yes.
    • Note: Refer to the Quality Value.
  • libreoffice-pdf-convert-engine-aliases
    • Description: Set a list of aliases to be used in the variable injection expression. Works in conjunction with the libreoffice-convert-engine-aliases.
    • Required: Yes.
    • Note: Supports the Variable Substitution.
  • libreoffice-pdf-convert-engine-dpi
    • Description: Set the DPI of all images.
    • Required: No.
    • Note: Refer to the MaxImageResolution.
  • libreoffice-pdf-convert-engine-use-tagged-pdf
    • Description: Whether a Tagged PDF must be created.
    • Required: No.
    • Note: Refer to the Tagged PDF.
  • libreoffice-pdf-convert-engine-export-notes-pages
    • Description: Set whether notes also need to be exported.
    • Required: No.
  • libreoffice-pdf-convert-engine-export-only-notes-pages
    • Description: Set whether only notes need to be exported.
    • Required: No.
  • libreoffice-pdf-convert-engine-single-page-sheet
    • Description: Set whether each sheet is exported as a single page.
    • Required: No.
  • libreoffice-pdf-convert-engine-skip-empty-pages
    • Description: Set whether empty pages must be skipped.
    • Required: No.
  • libreoffice-pdf-convert-engine-magnification
    • Description: Set the magnification:
      • 0: Default.
      • 1: Entire page.
      • 2: Entire page width.
      • 3: Entire box width.
    • Required: No.
  • libreoffice-pdf-convert-engine-rasterize
    • Description: Set whether a PDF must consist of a series of raster images, rather than special objects.
    • Required: No.
  • libreoffice-pdf-convert-engine-page-range
    • Description: Set the page range. It can be represented using the following rules:
      • 1: Represents a regular page number.
      • 1,2: Represents a comma-separated list of pages.
      • 1-10, -10, 1-: Represents a range selection with an optional beginning and ending.
      • 1,2;3;4-10;20: Represents a combination of all the above.
    • Required: No.
LibreOffice HTML Convert Engine

These constants control the LibreOffice-based HTML convert engine.

  • libreoffice-html-convert-engine-aliases
    • Description: Set the closing tag for variable injection expression. Works in conjunction with the libreoffice-convert-engine-aliases.
    • Required: Yes.
  • libreoffice-html-convert-engine-skip-header-footer
    • Description: Set whether the header and footer must be skipped.
    • Required: No.
  • libreoffice-html-convert-engine-embed-images
    • Description: Set whether all images must be embedded.
    • Required: No.
  • libreoffice-html-convert-engine-skip-images
    • Description: Set whether no images must be included.
    • Required: No.
  • libreoffice-html-convert-engine-no-line-limit
    • Description: Set whether no line limit restriction must be applied.
    • Required: No.
Tar Convert Engine

These constants control the tar convert engine.

  • tar-convert-engine-compression
    • Description: Set the output compression.
    • Required: Yes.
    • Note: Refer to the Compression Value.
  • tar-convert-engine-flatten-dir
    • Description: Set whether no directories must be created inside archives.
    • Required: Yes.
  • tar-convert-engine-timestamp
    • Description: Set the timestamp of all archive entries.
    • Required: No.
ZIP Convert Engine

These constants control the ZIP convert engine.

  • zip-convert-engine-compression
    • Description: Set the output compression.
    • Required: Yes.
    • Note: Refer to the Compression Value.
  • zip-convert-engine-flatten-dir
    • Description: Set whether no directories must be created inside archives.
    • Required: Yes.
  • zip-convert-engine-timestamp
    • Description: Set the timestamp of all archive entries.
    • Required: No.
    • Note: ZIP dates are special and start at 1980-01-01 00:00, which is 315532800 in integer notation.

run

This field declares script receipts that can be invoked via the Run Command.

A syntax for these scripts is powered by Nushell. This shell provides built-in path manipulations, globbing, looping, typed variables, filters, functional programming features, parsing files, working with datetime, and many other functionalities. And most importantly, it is a single binary that does not require a complete shell environment like bash + busybox.

Before being run, any script is piped through the golang template engine. Besides various numbers of template language structures, few more special actions are also available:

  • .Root: The root directory of the Unistore.
  • .Target: The name of the currently identified and running target. Refer to the Target Detection section for detailed information.
  • .Arguments: An array of command line arguments passed to this script (i.e., after the --). Proceed to the Run Command for details.
  • .ArgumentsLine: The same as above, but in a single string format.
  • varbin: A function that resolves the binary under dirs.var or instead falls back to the system one.

Examples

Run pip:

run.pip = """
(
    {{varbin "python"}}
    -m pip 
    {{.ArgumentsLine}}
)
"""

Print some information about the currently running target:

run.info = """
let target = "{{.Target}}" | split row -
let os = match ($target | first) {
    "linux" => "GNU/Linux",
    "nt" => "Microsoft Windows",
    _ => "Unknown"
}

print $"OS: ($os), Arch: ($target | last)"
"""

See also:

  • https://www.nushell.sh/book/variables_and_subexpressions.html#variables
  • https://www.nushell.sh/commands/docs/split_row.html#frontmatter-title-for-stringss>
  • https://www.nushell.sh/cookbook/pattern_matching.html#using-the-match-keyword
  • https://www.nushell.sh/book/stdout_stderr_exit_codes.html#echo-print-and-log-commands
  • https://www.nushell.sh/book/working_with_strings.html#string-interpolation

List all scripts in the run field:

run.ls-scripts = """
(ls -f {{.Root}}/*.toml)
    | each {|f| open $f.name}
    | where {|f| ($f | get -i magic) == "!UNISTORE-ROOT-ECF8"}
    | first
    | get run 
    | columns
"""

Also refer to the following:

  • https://www.nushell.sh/commands/docs/ls.html
  • https://www.nushell.sh/commands/docs/open.html
  • https://www.nushell.sh/commands/docs/get.html
  • https://www.nushell.sh/commands/docs/where.html
  • https://www.nushell.sh/commands/docs/first.html
  • https://www.nushell.sh/commands/docs/columns.html

Run the nested Unistore entry:

run.help = """
[
    {subcommand: enter, color: green},
    {subcommand: run, color: yellow},
    {subcommand: find, color: purple},
] | each {|record|
    let stdout = do { 
        unistore help $record.subcommand 
    } | complete | get stdout
    print $"(ansi $record.color)($stdout)(ansi reset)"
}
"""

More information can be found below:

  • https://www.nushell.sh/book/types_of_data.html#records
  • https://www.nushell.sh/book/types_of_data.html#tables
  • https://www.nushell.sh/commands/docs/each.html#frontmatter-title-for-filters
  • https://www.nushell.sh/book/variables_and_subexpressions.html#variables
  • https://www.nushell.sh/book/stdout_stderr_exit_codes.html#exit-code
  • https://www.nushell.sh/book/stdout_stderr_exit_codes.html#echo-print-and-log-commands
  • https://www.nushell.sh/book/working_with_strings.html#string-interpolation
  • https://www.nushell.sh/commands/docs/ansi.html#frontmatter-title-for-platform

Tag Configuration File

The Tag Configuration File is used to declare a list of tags and their corresponding file-matching expressions. The structure of this file is straightforward, intuitive, and user-friendly.

It is common to have multiple such files, each defining mutually complementary sets of tags. Any file can be assigned to multiple tags and be a part of multiple patterns. On the other hand, any directory cannot be tagged at all, but can still be used in the pattern expression.

The Find Command primarily utilizes these configuration files. Further details on usage and file lookup can be found in the documentation section of this command.

magic

This field has a special meaning and represents the version of the Unistore tag subsystem.

Currently supported value is !UNISTORE-TAG-ECF8.

Examples:

magic = "!UNISTORE-TAG-ECF8"

tags

This field is used to directly specify tags and their associated patterns.

If some tag was already declared previously by other the Tag Configuration Files, the patterns they proclaim do not contradict, but complement each other.

The type of this field is a table, where the key is the name of the desired tag, and the value is an array of file-matching patterns.

The key format is restricted to the TOML Specification. Hence, complex tags with spaces, special symbols, and Unicode characters are possible but not encouraged.

The value format follows the usual matching rules used by many programs and libraries, such as fnmatch, glob expressions, and pattern matching:

  • *
    • Matches any sequence of non-path separator(/) characters.
  • **
    • Matches zero or more directories. Due to recursive matching being a common need, it is the default behavior, e.g. dir/subdir is the same as dir/subdir/**. However, this behavior is not applied to an expression that points to the file.
  • ?
    • Matches any single non-path separator(/) character.
  • {a,b,c}
    • Matches a sequence of characters against any member of the given group.
  • [class]
    • Matches any single non-path separator character against a class of characters. A class can be given in the following forms:
      • [abc]: Any within the set.
      • [a-z]: Any within the range.
      • [^abc]: Any not within the set.
      • [!abc]: Any not within the set.

Examples:

tags.videos = ["./media"]
tags.images = [
    "../share/{resouces,downloads}/*.jpg"
]
tags.skip = ["./scans/scan-0[1-5].jpg"]

override

This field is used to specify the most significant tags and patterns to match files against these tags.

An arbitrary file matched by tags declared in this field invalidates any similar declarations for that file in the tags field, including any other resolved Tag Configuration File.

Such a file can only be assigned to a single tag from this field. Declaring multiple tags for the same file is discouraged; the resulting tag can be any of these.

For all other matters, this field follows the same rules as the tags field does: multiple declarations are merged across the Tag Configuration Files, and the key and pattern expressions use the same syntax. Please refer to the tags section for more information.

Examples:

override.tmp = ["./project/generated"]
override.priv = [
    "./share/names/department.*"
]

Variable Configuration File

The Variable Configuration file serves to announce clearly identified and configurable values throughout the Unistore.

The rationale behind introducing a particular configuration file, as opposed to delegating such tasks to build scripts, is as follows:

  • It facilitates the segregation of concerns and promotes organizational clarity.
  • It allows for inheritance across multiple files.
  • It integrates seamlessly with the Tag Configuration File.

The Variable Configuration File is commonly utilized to inject variables into documentation files via the LibreOffice convert engine, thereby expanding upon frequently used and/or private information.

The variable configuration file has no constraints onto its internal structure, except for the magic field.

Thereby, any complex values are allowed, including nested tables, floats, booleans, date-times, and more. The only exclusion out of these rules is an array of tables, as it makes the referencing data using a simple string identifier impossible. Also visit the Access Variable Configuration File for a brief example of direct variable manipulation.

Variable Substitution

The Variable Configuration file also supports an inline substitution.

When the string value of an arbitrary key is prefixed with the @ symbol, this value will be replaced with the corresponding key the string value points to.

The type of the value that is being substituted is not limited to strings and may include nested tables, for example. Please note that the discovery of the key to replace the current value is not restricted to the current file; it is performed for the entire environment. That means that it is possible to reference keys declared in other files, as long as they have already been discovered and processed.

Examples:

[me]
name = "Toccata"

[alterego]
name = "Vivaldi"

[documents]
table.author = "@me"
slide.author = "@alterego"

magic

This field is specific to the process of determining the generation of the variable configuration file.

Presently, there is only one generation: !UNISTORE-VAR-ECF8.

Examples:

magic = "!UNISTORE-VAR-ECF8"

Examples

[self]
happy = false
statuses = ["sad"]
name = { first = "Toccata", last = "and Fugue" }

[extra.info]
epoch = 1970-01-01 00:00:00Z
pi = 3.14159265359

Please refer to the TOML Specification for more information.

Usage

Help Command

A default command if no other arguments are given.

In the absence of additional arguments, it provides a short overview of all available commands and flags. Alternatively, when specifying a particular command, it gives detailed details pertaining to that command.

Flags:

  • -v / --verbosity
    • Enable verbose output.
  • --version
    • Print the Unistore version and exit.

Examples:

  • unistore help
  • unistore --help
  • unistore help run
  • unistore help find

Enter Command

This commands executes a Nushell, changing the current directory to the root of the Unistore and adding this particular binary into the PATH.

Note that behavior differs, according to the platform. On Windows, a new window is created; while on GNU/Linux, FreeBSD, and other POSIX systems, execve system call is invoked instead.

This is a default command on Windows, when binary is started with no attached console (likely when double-clicking in Explorer).

Flags:

  • -v / --verbosity
    • Enable verbose output.

Examples:

  • unistore enter

Run Command

This command runs a script listed in the Root Configuration File.

Note that this command is default if at least one argument is passed.

Before executing, the script is also piped through a template engine. Refer to the run field of the Root Configuration File for more details.

Additional arguments that are expected to be passed into the target script have to be passed after double hyphen (--).

Flags:

  • -v / --verbosity
    • Enable verbose output.

Examples:

  • unistore run myscript -- all
  • unistore myscript -- all

Find Command

This command finds a set of files that match some particular or special tag.

Firstly, the program discovers all the Tag Configuration Files recursively both down and up in the directory tree. It respects the lookup.skip patterns and stops if the root of the Unistore is reached.

Secondly, it tries to look up recursively down in the directory tree for all the files that match requested tags.

Arguments can be given in the following form:

  • A single tag.
  • A comma- or space-separated list of tags.
  • The special value all or *, which indicates a search for all possible tags.
  • The special value none, which indicates a search for all files that have no assigned tag.

Flags:

  • -v / --verbosity
    • Enable verbose output.
  • --no-concurrency
    • Disable concurrency. Lowers memory usage but also slows down the whole process.
  • -c / --collect
    • Print a table of requested tags and number of affected files with their sizes.
  • -d / --dir
    • Directory to work from (default is the current working directory).

Examples:

  • unistore find mytag
  • unistore find -c all
  • unistore find none
  • unistore find --no-concurrency --collect tag1,tag2

Startup Details

Note that the Unistore is daemonless and stateless (makes no use of lock files/sockets). However, this may not be the same for some dependencies. For example, for parallel processing, LibreOffice may require additional setup of a temporary profile, which will slow down document conversion.

Startup Routine

The startup routine is as follows:

  • Traverse the current directory tree up until the Root Configuration File with the magic field is found.
  • Read the contents of the Root Configuration File.
  • Detect the current running target. For example, on GNU/Linux, a version of C standard library is examined. Refer to the Target Detection for further details.
  • Check if directory under the dirs.var/{target} exists:
    • If it does, proceed to the next.
    • If it does not, extract the embedded bundle into this directory.
  • Handle the requested command.

Target Detection

The Unistore threats:

  • 64-bit systems as x86_64
  • 32-bit systems as i686
  • The Microsoft Windows operating systems family as nt
  • GNU/Linux distributions as linux-glibc or linux-musl, depending on the libc implementation

Examples:

  • nt-x86_64
  • linux-glibc-x86_64

Other targets may have some inconsistencies due to the varied nature of this determination (where Unistore entry uses go and the Unistore package uses python), but it should generally function across all operating systems (e.g., Plan9, FreeBSD, etc.).

Unistore Python Package

The Unistore Python Package is a lightweight toolset that provides access to various functionalities offered by the Unistore. It can be utilized in the following number of ways:

  • Utilized within code through an import statement.
  • Invoked directly via the command-line interface as a module.
  • Accessed through exported tasks from Luigi build scripts.

The startup routine of the Unistore Python Package includes the discovery of the Root Configuration File and the Variable Configuration Files. It also respects all related notions such as the lookup.skip.

Convert Function

The core of this package is a unistore.operations.convert function. This function is invariably invoked upon for any convert operation, regardless of the origin of the operation request.

The convert function is driven by a simple idea: defining pending operation as a set of rules, where each rule maps inputs to outputs. It seamlessly integrates wildcard support in a Pythonic manner.

The convert function takes responsibility for many complex processes, and most notably the following key aspects:

  • Management of output and input rules.
  • Expansion of wildcards and resolution of paths.
  • Omission of up-to-date files.
  • Removal of outdated output files.
  • Determination of operation types.
  • Injection of additional parameters.
  • Caching of reusable instances.

Convert Engine

A logical supplement to the convert function is a concept of a convert engine. It is directly accountable for executing convert operation, i.e., generating output file. A concept of convert engine also allows focusing on the convert operation itself, eliminating the need to grapple with wildcard expansion and other intermediate steps.

Below is the list of built-in convert engines:

  • archives (unistore.engines.archives)
    • TarConvertEngine
    • ZipConvertEngine
  • documents (unistore.engines.audios)
    • LibreOfficeConvertEngine
    • LibreOfficePDFConvertEngine
    • LibreOfficeHTMLConvertEngine
  • strip (unistore.engines.strip)
    • StripConvertEngine
  • ffmpeg (unistore.engines.ffmpeg)
    • FFMpegConvertEngine
  • audios (unistore.engines.audios)
    • FFMpegAudioConvertEngine
    • FFMpegOpusConvertEngine
    • FFMpegCopyAudioConvertEngine
    • FFMpegDiscardAudioConvertEngine
  • images
    • FFMpegAVIFConvertEngine
    • FFMpegJpegXLConvertEngine
    • FFMpegWebPConvertEngine
    • FFMpegJpegConvertEngine
  • videos
    • FFMpegVideoConvertEngine
    • FFMpegVP9ConvertEngine
    • FFMpegAV1ConvertEngine
    • FFMpegNvEncConvertEngine
    • FFMpegAVCConvertEngine
    • FFMpegCopyVideoConvertEngine
    • FFMpegDiscardVideoConvertEngine

Logging

The Unistore Python Package uses log tags to configure the verbosity of the output. Logging configuration can only occur once per run due to the nature of cached instances.

Regardless of the configuration method, log tags must be provided in the form of a comma-separated list, where each element must satisfy one of the following:

  • A name of the submodule in the unistore module:
    • config, operations, engines, luigi
  • A special value all or * that includes all possible tags.

To set the verbosity level, one may utilize the UNISTORE_LOG_TAGS environmental variable or a more specific approach, such as passing a command-line argument when invoking via the command-line interface. Please refer to the corresponding section for more information about certain logging tuning.

Code Samples

Configure Logging

For more information about the unistore.get_store function, refer to the __init__.py.

import unistore

_ = unistore.get_store(tags="config,operations")

Access Root Configuration File

The complete definition of StoreConfig can be found at the config.py.

import unistore

if __name__ == "__main__":
    config = unistore.get_store().config
    
    print("The Root Configuration File is located at", config.get_path())
    print("  Magic value:", config.magic)
    print("  Python:", config.dirs.locate_binary("python"))
    print("  Scripts:", ", ".join(config.run.keys()))

Access Variable Configuration File

import unistore

if __name__ == "__main__":
    print("self.statuses =", unistore.get_store().vars["self.statuses"])

Access Constants

import unistore

if __name__ == "__main__":
    store = unistore.get_store()
    
    print("LibreOffice PDF Convert Engine constants:")
    for p in filter(
        lambda p: p.startswith("libreoffice_pdf"),
        dir(store.config.constants),
    ):
        print(f"  {p} = {getattr(store.config.constants, p)}")

Run External Tool

import unistore.operations

if __name__ == "__main__":
    exit_code = unistore.operations.run(
        binary="whoami", shell=False, env={}, check_code=False
    )
    print("Exit Code:", exit_code)

Run Convert Operation

This snippet will automatically guess the required convert engine.

Note that when the output extension matches that of the input, the Strip Convert Engine is utilized.

import unistore.operations

if __name__ == "__main__":
    unistore.operations.convert(
        rules={"mnt/images/image.png": "dist/image.avif"}
    )

Run Convert Operation with Wildcards

import unistore.operations

if __name__ == "__main__":
    unistore.operations.convert(
        rules={"mnt/images/image-*-*.png": lambda f, s: f"dist/image-({f}-{s}).avif"}
    )

As can be seen from the snippet above, if the input rule includes wildcard pattern(s), the corresponding output rule must be a callable function with a number of parameters equal to the number of patterns. The arguments passed to this function will represent the matched path parts.

Run Convert Operation with Overrides

from unistore.operations import convert
from unistore.engines.arguments import Quality, Compression

if __name__ == "__main__":
    convert(
        rules={"mnt/images/image.png": "dist/image-bad.avif"},
        override="yes",
        # engine_quality=Quality.BAD,
        engine_quality="bad",
        # engine_compression="extreme",
        engine_compression=Compression.EXTREME,
    )

Please note the following:

  • Required overrides must be prefixed with engine_.
  • Practically, overrides are injected into the constructor of the convert engine. Notationally, they correspond to the Constants section, with a slight variation: the name of the convert engine must be removed from the beginning of constant name. For instance, to inject ffmpeg_opus_convert_engine_quality, use engine_quality.
  • Unsupported overrides are silently ignored. The rationale behind this is to allow overriding multiple constants for multiple convert engines.
  • override and mkdirs are the only constants passed to the convert function and not to the convert engines. Therefore, they are not prefixed.

Run Convert Operation with Explicit Convert Engine

from unistore.operations import convert
from unistore.engines.images import FFMpegAVIFConvertEngine

if __name__ == "__main__":
    convert(
        rules={"mnt/images/image.png": "dist/image-75.avif"},
        engine_factory=(
            FFMpegAVIFConvertEngine, 
            lambda: FFMpegAVIFConvertEngine(quality=75),
        ),
    )

Run Convert Operation with Self-Written Convert Engine

from unistore.operations import convert


class HelloWorldConvertEngine:
    def apply(self, input_file, output_file):
        self.input_file = input_file
        self.output_file = output_file

    def run(self, working_dir):
        self.output_file.write_text(
            "\n".join([self.input_file.read_text(), "Hello, world!"])
        )


if __name__ == "__main__":
    convert(
        rules={"mnt/texts/text-*.txt": lambda w: f"dist/hello-world-{w}.txt"},
        engine_factory=(HelloWorldConvertEngine, lambda: HelloWorldConvertEngine()),
        override="yes",
    )

Please note that the convert engine may behave differently according to the rules:

  • For a single input and a single output:
    • A single instance of the convert engine is utilized.
    • The apply method is invoked once for each instance.
  • For multiple inputs and a single output:
    • A single instance of the convert engine is utilized.
    • The apply method is invoked multiple times for each input, while the output remains the same.
  • For multiple inputs and multiple outputs:
    • Multiple instances for each input and output pair are utilized.
    • The apply method is invoked once for each instance.

To protect the particular convert engine from being misused for multiple inputs, a simple self-written lock variable can be used:

class LockConvertEngine:
    def __init__(self):
        self.applied = False

    def apply(self, input_file, output_file):
        if self.applied is True:
            raise ValueError("Cannot use this Convert Engine for multiple inputs.")

        self.applied = True

Alternatively, the utility method unistore.engines.ConvertEngineUtil.single_apply_guard is available to be utilized:

from unistore.engines import ConvertEngineUtil


class UtilConvertEngine:
    def apply(self, input_file, output_file):
        ConvertEngineUtil.single_apply_guard(self, self.apply)

Run Convert Operation with Self-Written Convert Engine for Multiple Inputs

import pathlib

from unistore.operations import convert
from unistore.engines import ConvertEngine


class ConcatConvertEngine:
    def __init__(self):
        self.inputs: list[pathlib.Path] = []
        self.output: pathlib.Path | None = None

    def apply(self, input_file: pathlib.Path, output_file: pathlib.Path) -> None:
        self.inputs.append(input_file)
        self.output = output_file

    def run(self, working_dir) -> None:
        content = "\n".join([inp.read_text() for inp in self.inputs])
        self.output.write_text(content)


if __name__ == "__main__":
    # `ConvertEngine` is a runtime-checkable protocol
    assert(isinstance(ConcatConvertEngine(), ConvertEngine))

    convert(
        rules={"mnt/texts/text-*.txt": lambda w: "dist/concat.txt"},
        engine_factory=(ConcatConvertEngine, lambda: ConcatConvertEngine()),
        override="yes",
    )

Command-Line Interface

The Unistore Python Package provides the command-line interface that represents a simple wrapper over the unistore.operations.convert function. It is supposed to serve as a lightweight tool for simple conversion operations, eliminating the need for writing an appropriate script.

The Unistore python package can be invoked directly as a module as stated in the Executing modules as scripts:

python -m unistore

Although the recommended way to invoke this module is to use a script in the Root Configuration File:

#
# 'convert' executes the Unistore python package as the command-line interface module.
#
run.convert = """
(
    UNISTORE_LOG_TAGS="operations,engines"
    {{varbin "python"}} -m unistore {{.ArgumentsLine}}
)
"""

This effectively allows running it with a short command in a portable way:

unistore convert -- <args>

Flags:

  • --working-dir
    • Set the current working directory. Defaults to the current working directory.
  • --override <yes,no,uptodate>
    • Override the default override policy. Refer to the cli-override for more info.
  • --mkdirs
    • Override the default mkdirs policy. Refer to the cli-mkdirs for more info.
  • -v / --verbose
    • Enable verbosity. If set, takes a higher priority than the UNISTORE_LOG_TAGS environmental variable.
  • --engine-<*>
    • Override constant. Please refer to the Run Convert Operation with Overrides section for detailed explanation.
  • --help
    • Print the help message and quit.

Examples:

Diagnose config-related problems:

unistore convert -- _ _ --verbose


Convert JPEG image to JPEG XL, with the quality parameter set to 30%:

unistore convert -- image.jpg image.jxl --engine-quality 30


Strip metadata of a PDF file:

unistore convert -- document.pdf document.pdf --override=yes

Luigi

Build scripts can be enhanced by the Luigi project.

Unlike many other build systems, luigi tasks seem minimalistic, yet allowing for simple cross-task parameters, making them easily understandable even to non-Python users.

However, said above simplicity does not imply an inability to handle complex scenarios. Even more of that, Luigi offers built-in support for a variety of features including:

  • Central scheduler with web interface.
  • Complex task graphs.
  • Configuration management.
  • Integration with various file systems (HDFS, S3, FTP, SQL, Spark, Hadoop).
  • Task status tracking.
  • Event handling and callbacks.
  • Namespaces management.
  • And more.

This section does not cover all possible scenarios and usage cases. For further details on advanced usage, API documentation, and more, visit the Luigi documentation.

Typical build scripts built with the Unistore package and Luigi are short, clear and sharp. They usually consist of nothing more than a single class with a simple method.

The overall attitude of the Unistore package to change a regular Luigi environment is to do as fewer modifications as possible, surely making them optional. This brings some complications such as a completion faking, and related limitations, but does not repeal previously declared rules.

It is also highly recommended to examine the content of the Code Samples section. That section covers the fundamentals of the convert operation; provided examples can also be adapted for use within the Luigi environment as needed.

Running Luigi

Luigi is a python package and can be invoked as any other module directly. Please refer to the Executing modules as scripts and Running Luigi for additional details about Luigi startup.

The recommended approach to run Luigi is to use the following script that needs to be declared in the Root Configuration File.

#
# 'build' executes build.py script as a luigi module.
#
build = """
(
    UNISTORE_LOG_TAGS="operations,engines"
    {{varbin "python"}} -B -m luigi
    --local-scheduler
    --log-level INFO
    --module build
    {{.ArgumentsLine}}
)

This script will ensure that all requirements listed below are met:

  • The resulting invocation command is brief enough, unistore build -- mytask.
  • The execution process leaves no __pycache__.
  • Debug messages from Luigi are omitted.
  • The local scheduler is started instead of the Central Scheduler.

Convert Engine Wrappers

The unistore.luigi submodule defines a set of wrappers over the convert engines listed in the Convert Engine section.

These are termed wrappers because they are plain classes designed to seamlessly integrate with the Luigi environment.

In contrast to how the Run Convert Operation with Overrides is applied for regular Python code, the submodule takes advantage of using Luigi Parameters.

Hence, instead of the flexible engine_ and the explicit but complex engine_factory keyword arguments, the submodule provides corresponding tasks with parameters that are precisely match the constants listed in the Constants section.

Here are the available Luigi tasks:

  • generic (unistore.luigi)
    • luigi_run
    • luigi_convert
  • archives (unistore.luigi)
    • tar_convert_engine
    • zip_convert_engine
  • documents (unistore.luigi)
    • libreoffice_convert_engine
    • libreoffice_pdf_convert_engine
    • libreoffice_html_convert_engine
  • strip (unistore.luigi)
    • strip_convert_engine
  • ffmpeg (unistore.luigi)
    • ffmpeg_convert_engine
  • audios (unistore.luigi)
    • ffmpeg_audio_convert_engine
    • ffmpeg_opus_convert_engine
    • ffmpeg_copy_audio_convert_engine
    • ffmpeg_discard_audio_audio_convert_engine
  • images (unistore.luigi)
    • ffmpeg_avif_convert_engine
    • ffmpeg_jpeg_xl_convert_engine
    • ffmpeg_webp_convert_engine
    • ffmpeg_jpeg_convert_engine
  • videos (unistore.luigi)
    • ffmpeg_video_convert_engine
    • ffmpeg_vp9_convert_engine
    • ffmpeg_av1_convert_engine
    • ffmpeg_nvenc_convert_engine
    • ffmpeg_avc_convert_engine
    • ffmpeg_copy_video_convert_engine
    • ffmpeg_discard_video_convert_engine

Declare Genuine Luigi Task

import pathlib
import luigi


class all(luigi.Task):
    hello = luigi.OptionalStrParameter(default="hello")
    world = luigi.OptionalStrParameter(default="world")

    def output(self):
        return luigi.LocalTarget("dist/luigi-hello-world.txt")

    def run(self):
        pathlib.Path(self.output().path).write_text(", ".join([self.hello, self.world]))

The command-line arguments --all-hello= and --all-world= can be specified to override the hello and world parameters, respectively. To conform to the widely accepted Utility Convension, it is recommended to give lowercase name for tasks, but this recommendation can be safety ignored.

Declare Task with Unistore Stub

import luigi
import pathlib
import unistore.luigi


class all(unistore.luigi.EmptyTask):
    def runs(self):
        pathlib.Path("dist/luigi-stub.txt").write_text(", ".join([self.hello, self.world]))

Due to the unistore.convert function being stateless (it resolves inputs and outputs and then executes them immediately), the unistore.luigi.EmptyTask task is provided for use.

This stub task reports that the current task is incomplete and needs to be run unconditionally. Without this solution, the task would result in an error, as it does not declare any inputs and outputs to be tracked by Luigi.

Using the runs method is formally the same as the run and the only difference is a completion faking.

Run Convert Operation with Luigi

import luigi
import unistore.luigi


class all(unistore.luigi.EmptyTask):
    def requires(self):
        return unistore.luigi.ffmpeg_jpeg_xl_convert_engine(
            rules={"mnt/images/image.png": "dist/image-luigi-requires.jxl"},
            quality="best",
        )

    def runs(self):
        yield unistore.luigi.ffmpeg_jpeg_xl_convert_engine(
            rules={"mnt/images/image.png": "dist/image-luigi-runs.jxl"},
            quality="best",
        )

The difference between requires and runs is as follows:

  • According to the Luigi documentation, requires is designed for static dependencies, while runs is intended for dynamic ones.
  • When runs encounters the yield keyword, it will resume from scratch. Thus, it's crucial to ensure that a task is not executed multiple times, either by manual validation or by setting the Override policy.
  • While requires executes tasks in an arbitrary order and continues even if any of them fail, runs executes tasks in the order they are yielded and halts promptly if any task fails.
  • Unlike requires, runs does not need to return a value and uses yield instead, making the method more logically convenient to write.

Please also note that not only can specific parameters in the currently executing class be overwritten, but also any other tasks that are executed. For instance, the --ffmpeg-jpeg-xl-convert-engine-compression argument can be passed via the command-line interface to override the Compression Value of the FFMpeg JPEG XL Convert Engine.

Run Convert Operation from SubTask

import luigi
import unistore.luigi


class convert_ghost(unistore.luigi.EmptyTask):
    output_name = luigi.OptionalStrParameter(default="dist/luigi-subtask.jxl")

    def runs(self):
        yield unistore.luigi.ffmpeg_jpeg_xl_convert_engine(
            rules={"mnt/images/image.png": self.output_name},
            quality="best",
        )


class all(unistore.luigi.EmptyTask):
    def requires(self):
        return convert_ghost("dist/luigi-main-task.jxl")

Run Convert Operation with Convert Function

import unistore.operations
import unistore.luigi


class all(unistore.luigi.EmptyTask):
    def runs(self):
        unistore.operations.convert(
            rules={"mnt/images/*.png": lambda n: f"dist/{n}.jxl"},
            engine_quality="best",
        )

Building

Requirements

For both GNU/Linux distros and Windows:

  • Python >= 3.12
  • PDM package manager
  • Go

For GNU/Linux:

  • 7z (package name is probably p7zip)

Instruction

The Unistore build process is implemented using doit library. With the help of this tool, the following is achieved:

  • Separate build steps, with the corresponding dependency graph, error handling and help messages.
  • Portable binaries are downloaded on demand.
  • Support for caching.
  • Cleaning of intermediate files.
  • Injection of variables.
  • Lightweight codebase.

To begin with, utilize the subsequent:

python ./build.py TARGET=generic
python ./build.py TARGET=<target>

where <target> is a pair in the form <os>-<arch>. E.g.:

  • nt-x86_64
  • linux-glibc-x86_64
  • freebsd-x86_64

If no errors occurred, the final binary is expected to be placed in build/dist/<target>/unistore[.exe].

Customization

A build process may be customized if needed. In the same manner as TARGET is set in the Instruction section, any of these options can be overwritten:

  • DIST to set the directory to put build artifacts into.
  • RUN to set the directory to contain prepared data to be bundled inside the executable.
  • TMP to set the directory for intermediate artifacts used to form RUN.
  • COMPRESSION to set compression level for the Zstandard compression algorithm. Valid values range from negative integers to 22. Negative levels effectively engage --fast mode from the zstd CLI.
  • PACKAGE to set the directory pointing to the source code of the Unistore Python Package.
  • ENTRY to set the directory pointing to the source code of the Unistore Entry.

There is also a wide range of arguments that are understood by the doit, for example:

  • python ./build.py help
  • python ./build.py clean
  • python ./build.py list
  • python ./build.py info
  • python ./build.py strace

Common Questions

  • Any real examples that use this?

Sure, check out the Universe repository. They Unistore was specifically built for this project.

  • Why does a building process take so long?

Mainly because a zip + zstd couple is not widely supported (even though it is a part of the specification).

Why zip? Because it is a popular random-access archive format that can be effectively extracted concurrently.

This way, unfortunately, I could not find any reliable solution to create a zip file with zstd compression method. The best solution is windows-specific 7-Zip-Std, while any alternatives like libarchive/bsdtar are not capable of this.

Therefore, a monkey-patched library zipfile-zstd is used.

  • Can the Unistore package (python script) communicate with the Unistore entry (go binary)?

The answer is that it depends.

Running any script through the Unistore entry (unistore run) is nothing but a simple substitution of dirs.var. Therefore, no additional startup modification steps are taken; no sockets, queues, named pipes or any IPCs mechanisms are created.

However, it does not mean that this is impossible. Any script in the run section of the Root Configuration File can spawn multiple processes and connect them.

  • Is there a possibility to use a different working directory?

Yes.

The Find Command, for instance, may receive the -d/--dir argument.

As for the Unistore Python Package, the unistore.get_store function can be called at the very beginning of the execution, setting the working_dir parameter. A similar approach can be found in the Configure Logging section.

The same applies to the unistore.operations.convert and the unistore.operations.run functions. They both accept the working_dir argument and never use relative paths.

And of course, for scripts declared in the run section, cd may be used.

  • Variables such as {$@me$} are not substituted, but they are set in varfile.toml. What should I do?

This probably happens either because the word processor is using spell-checking or RsidRPr (revision identifier).

Try to select the entire paragraph, then set a language to English (US) and disable spell-checking.

Should the issue persist, attempt to access the document as a zip archive and review its XML files. It is possible that some of these files still contain extraneous tags.

  • Why there are no commits?

Because I was using Duplicity as a local backup solution rather than a proper version control system. My bad 🙃

  • I'm trying to do unistore enter from the Windows Terminal and it launches a new window. Any workarounds?

Probably, a Powershell script needs to be created that starts Nushell and adds the Unistore entry to the PATH.

This is because execve is fundamentally broken on Windows. It does not replace the current process as expected; instead, it spawns a new process, which leads to many inconveniences, especially when running from an existing shell.

It is unlikely that keeping a new shell as the parent process and waiting for its termination will be implemented.

Credits

  • Go programming language
  • doublestar
  • humanize
  • compress
  • go-toml
  • table
  • cobra
  • Python programming language
  • python-build-standalone
  • pydantic
  • glob2
  • loguru
  • luigi
  • lxml
  • ruff
  • black
  • pyright
  • pdm
  • pyzstd
  • request
  • aiohttp
  • doit
  • exiftool
  • FFmpeg
  • LibreOffice
  • Nushell
  • QPDF
  • Many other cool open source projects that depend on or are missing from the above.

Without such tools, the Unistore would never reach its goals! Praise the open source community!

Thanks for reading this document and taking your time for this creation.

License

This project is licensed under the MIT License. You are free to use, modify, and distribute this software, but please provide attribution.

About

A portable project management environment for an extensive collection of diverse solutions.

Topics

build-toolexiftoolffmpeglibreofficeluiginushellportableproject-explorerproject-managementqpdftaggingtags

Resources

Readme
MIT license
Activity

Stars

0 stars

Watchers

0 watching

Forks

0 forks
Report repository

Contributors

Languages

You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.