- Overview
- Options Pages
- Command Line
- Shortcuts
- Plugins
- Generated Installer Details
- NSIS API Unit Testing
Adds rules for creating NSIS installers for bazel.
This project was originally inspired by CPack, but design and approach has since started to diverged.
bazel_dep(name = "rules_nsis", version = "<version>")
nsis = use_extension("@rules_nsis//nsis:extensions.bzl", "nsis")
# Currently 3.11 is the only supported version.
nsis.executable(name = "nsis", version = "3.11")
use_repo(nsis, "nsis_tool", "nsis_toolchains")
register_toolchains("@nsis_toolchains//:all")The Windows x86 zlib dependency is downloaded from SourceForge first. If that
download fails, Bazel builds upstream zlib 1.3.1 from GitHub sources with a
Windows x86 platform transition and a pinned Zig compiler. It cross-compiles on
Linux/macOS and builds Windows binaries on Windows, producing a static library,
DLL, import library, headers, and license. Compilation failures are reported
normally; no bundled ZIP is used. The Windows bundle follows the layout in
NSIS Appendix G.
Building native makensis on POSIX still requires native zlib development
headers and libraries, as before; the Windows bundle does not replace them.
For a full list of options, see: https://registry.bazel.build/docs/rules_nsis
For installer examples, see the tests: ./tests/BUILD.bazel.
load("//nsis:defs.bzl", "nsis_component", "nsis_component_group", "nsis_installer")
nsis_component(
name = "my_minimal_component",
srcs = [":my_files"],
selection_mode = "default",
)
nsis_component_group(
name = "my_minimal_group",
components = [
":my_minimal_component"
],
)
nsis_installer(
name = "my_minimal_installer",
components = [
":my_minimal_group",
":my_minimal_component",
],
product = "My Minimal Product",
product_path = "My Minimal Product",
# Optional; defaults to "Uninstall.exe".
uninstaller_name = "Remove My Minimal Product.exe",
)- NSIS Toolchain for cross-platform use.
- Define installer attributes (version, product, etc.).
- Support Components and Component Groups.
- Install windows Services (uses
sc.exe). - Dependency Based Selections.
- Handle Stamping Installers
- EventLog Registry Entries
- Uninstall previous installs prior to install
- StartMenu and Desktop Shortcuts (
nsis_shortcut). - Options pages (
nsis_options_page) with persisted values. - Installer command line:
/COMPONENTS,/INSTTYPE,/OPTIONS=,/O:,/HELP. - Update Path (
add_to_pathonnsis_component). - Set Environment Variables. [Help Wanted]
- Don't prompt for components if all hidden or all required.
- Enable adding files directly to installer (add to hidden section).
Set signing_certificate on nsis_installer to a
rules_signing certificate target.
If the certificate uses password_env, pass that variable to the build with
--action_env=VARIABLE_NAME (or --action_env=VARIABLE_NAME=value).
The installer action preserves the signing environment, including on Windows.
An options page asks the user for values and hands them to your hooks. It is
built from three rules, all loaded from //nsis:defs.bzl:
nsis_option: one control.key(default: the rule name) must match[a-z][a-z0-9_]*. Other attrs:control,label_text,description,default,defaults,required,enabled_by,persist, plus the control-specificchoices,multi_select,min,max,max_length,lines,filter,save,must_existandaddress_types. Attrs a control does not use are rejected at analysis time.nsis_option_group: a group box aroundoptions, withlabel_textand an optionalenabled_by. Groups do not nest.nsis_options_page:options(options and groups, top to bottom),title,subtitle,text,positionandorder. The rule name is the page id ([a-z][a-z0-9_]*;shortcutsandsetupare reserved).
load("//nsis:defs.bzl", "nsis_installer", "nsis_option", "nsis_option_group", "nsis_options_page")
nsis_option(name = "enable_extras", control = "checkbox", label_text = "Install extras")
nsis_option(name = "extras_name", control = "text", default = "extra", required = True)
nsis_option(name = "port", control = "number", min = "1", max = "65535", default = "8080")
nsis_option(name = "mode", control = "droplist", choices = ["fast", "slow"])
nsis_option(name = "token", control = "password")
nsis_option_group(
name = "extras_group",
options = [":extras_name", ":port"],
enabled_by = ":enable_extras",
)
nsis_options_page(
name = "install_settings",
title = "Install Settings",
position = "after_directory",
options = [":enable_extras", ":extras_group", ":mode", ":token"],
)
nsis_installer(
name = "my_installer",
options_pages = [":install_settings"],
# ...
)Attach a page with nsis_installer.options_pages (always shown) or
nsis_component.options_pages (shown only when that component is selected, and
only with position = "after_components").
control |
Backing type | Value / default form |
Control-specific attrs |
|---|---|---|---|
checkbox |
bool | 1 or 0 |
|
number |
number_type |
decimal integer, signed 32-bit by default | number_type, min, max |
text |
string | any text | max_length |
password |
secret string | any text; never persisted | max_length |
radio |
enum | one of choices |
choices |
droplist |
enum | one of choices |
choices |
richedit |
multiline | text; stored on one line with \n and \\ escapes |
max_length, lines |
file_request |
file | absolute file path, Browse button | filter, save, must_exist |
dir_request |
dir | absolute directory, Browse button | must_exist |
combobox |
string | text with suggested choices |
choices, max_length |
listbox, sorted_listbox |
enum | one of choices; with multi_select a list (defaults is a list of strings, not default) |
choices, multi_select, lines |
date |
date | YYYY-MM-DD |
min, max |
ip_address |
ipv4 | a.b.c.d |
|
net_address |
net | IPv4, IPv6 or DNS name, optionally with port or prefix | address_types |
address_types is any of ipv4, ipv6, dns (at least one) plus
with_port and with_prefix; empty means ipv4, ipv6 and dns. String
defaults may reference NSIS variables such as $DOCUMENTS. Without a
default a value is unchecked, the number closest to 0 within min/max, an
empty string, or the first choice. required demands a non-empty value (not
for number, checkbox, radio, droplist and date).
number_type supports int8, uint8, int16, uint16, int32 (default),
uint32, int64, and uint64. Defaults, min/max, UI input and CLI values
are validated against that type's range without truncation. For example,
control = "number", number_type = "int64" accepts signed 64-bit decimal values.
Leading zeros and an optional sign are normalized; unsigned types reject
negative values other than negative zero.
position is one of after_welcome, after_license, after_directory and
after_components (the default); all of them are before the files are
installed. Pages at the same position are ordered by order, then by name. The
dialog layout is computed at build time; a page whose controls do not fit fails
the build, so split it into several pages.
enabled_by names a checkbox on the same page: the control (or the whole
group) is disabled while the checkbox is unchecked. Checkbox chains are
allowed, cycles are not.
persist is auto (default: persisted, except passwords), yes or no
(password with yes is an error). Persisted values named <page>.<key> live
under Software\...\<product>\Options: booleans use one-byte REG_BINARY
(00 or 01), 8/16/32-bit numbers use REG_DWORD, and strings use REG_SZ.
Lists use REG_MULTI_SZ, one string per item. Both int64 and uint64 use
REG_QWORD. Signed numbers use their two's-complement representation.
File and directory options use REG_SZ because their paths are already resolved;
%VARIABLE% references are not expanded. Multiline strings retain the escaped
\n and \\ representation in REG_SZ for compatibility with older values.
Empty strings remain explicit empty REG_SZ values, distinct from missing values.
Values are loaded again by the uninstaller and the next install (as upgrade
defaults). Legacy REG_MULTI_SZ scalars and REG_SZ numbers/booleans/lists
(lists as a|b) are still read. Loading does not rewrite these values, so the
previous uninstaller can consume its original registry format. The new installer
writes the appropriate types during installation, after uninstalling the old version.
The value of an option is available in every hook (also the uninstall hooks, from
the persisted copy) as ${Option_Get} <page> <key> $var. Page and key are
plain words, not strings.
!macro PostInstall_my_component OUTPATH
${Option_Get} install_settings port $0
${If} install_settings ${Option_IsSet} enable_extras
; checkbox is checked
${EndIf}
${Option_ListContains} list_page toppings "nuts" $1 ; $1 = 1 or 0
${Option_ListCount} list_page toppings $3 ; number of items
${Option_ListGet} list_page toppings 0 $4 ; first item
${Option_GetMultiline} text_page note $2 ; \n -> CRLF
${Option_Set} install_settings port 9090
!macroendA multi_select option is a list: Option_Get returns the name of an
nsArray holding the items (in the order of choices), so use Option_ListContains,
Option_ListCount and Option_ListGet rather than reading it as text. On the
command line and in /OPTIONS files, repeat the option for each item
(/O:page.key=a /O:page.key=b; repeated key= lines in the file).
Option_Get, Option_Set, Option_IsSet, Option_ListContains,
Option_ListCount and Option_ListGet work
unchanged in uninstall hooks; use ${un.Option_GetMultiline} there. Passwords
are not persisted, so uninstall hooks see their default.
Installer hooks can save one persistable option after changing it with
${Option_PersistOne} <page> <key> <kind>, without rewriting other options.
Use its backing kind (bool, int/int32, any supported number_type, list, or a string-backed
kind such as string, multiline, file or dir). This explicit API is for
persistable options only; do not use it for passwords or persist = "no".
Installers built by this ruleset understand the following switches, besides the
standard NSIS ones (/S, /D=, /NCRC). Switch names are case-insensitive.
Invalid input makes the installer print ERROR: ... to the console and exit
with code 2 (silent mode) or show a message box (interactive mode).
| Switch | Meaning |
|---|---|
/COMPONENTS=<list> |
Comma separated component names or group names. Absolute (a,b: exactly these, plus required ones) or relative (+a,-b: change the defaults). Dependencies are selected with their dependents; deselecting a required component or one that a selected component needs is an error. Mixing the two forms is an error. |
/INSTTYPE=<name> |
Start from an install type. Combine only with a relative /COMPONENTS. |
/OPTIONS=<ini> |
Read options from an INI file: one [<page>] section per page with key=value lines, and an optional [setup] section with components= and insttype= (the /COMPONENTS and /INSTTYPE equivalents). Unknown sections or keys are errors. |
/O:<page>.<key>=<value> |
Set one option. May be repeated; the last occurrence wins. |
/HELP[=<topic>], /? |
Print the help and exit with 0. Topic: usage, options, components, insttypes or all (default). |
/FORMAT=text|ini |
Help format. ini is a valid /OPTIONS file with the usage as comments; passwords are shown as <secret> in text output and left empty in ini output. |
/HELP-OUT=<file> |
Write the help to <file> (UTF-16LE) instead of the console. |
/TESTID=<id> |
Only for testable installers: isolates registry keys, mutexes and the product code. |
Option values are validated and canonicalised (yes, TRUE and on are all
1 for a checkbox; dates must be YYYY-MM-DD, ...). Precedence, lowest to
highest: defaults, persisted values of a previous install, /OPTIONS=, /O:.
Command line options are applied before any page is shown, so in an
interactive install they pre-fill the pages. The help reports the effective
state, so /HELP /COMPONENTS=+docs shows what that selection would install.
Setup.exe /S /COMPONENTS=+docs,-samples /O:install_settings.port=9090 /OPTIONS=answers.ini
Setup.exe /HELP=options /FORMAT=ini /HELP-OUT=answers.ini
nsis_installer also has an options_doc output group with JSON and Markdown
files (<name>_options_doc.json and .md) listing options, components and
install types, for documentation:
bazel build //:my_installer --output_groups=options_doc.
nsis_shortcut creates a .lnk to a file that an nsis_component installs.
List it in the component's shortcuts.
load("//nsis:defs.bzl", "nsis_component", "nsis_installer", "nsis_shortcut")
nsis_shortcut(
name = "app_shortcut",
target = ":app.exe",
display_name = "My App",
description = "Starts My App",
arguments = ["--gui"],
icon = ":app.ico",
locations = ["start_menu", "desktop"],
)
nsis_component(
name = "app",
srcs = [":app.exe", ":app.ico"],
shortcuts = [":app_shortcut"],
)
nsis_installer(
name = "my_installer",
components = [":app"],
shortcuts_desktop_default = True,
# ...
)| Attr | Meaning |
|---|---|
target |
Mandatory. One of the component's srcs (or its service_executable). |
target_subpath |
The file inside a directory (tree artifact) target; required exactly then. Relative, no . or ... |
display_name |
Name of the .lnk. Defaults to the rule name in Title Case. |
description, arguments |
Comment and command line arguments (quoted as needed). |
icon, icon_subpath, icon_index |
Icon source, installed by the same component (default: the target's icon); icon_index also applies to the target's icon. |
locations |
Any of start_menu, desktop, path. Default ["start_menu", "desktop"]. |
start_menu_subfolder |
A folder below the user's Start Menu folder (start_menu only). |
location_path |
The folder for path (required exactly then): a drive or UNC path, or one starting with a shell constant such as $INSTDIR, $SMSTARTUP, $APPDATA. |
The "Start in" folder is the target's folder. Two shortcuts with the same name in
the same location fail the build. Shortcuts are created after the files and all
post_install hooks, only for installed components.
nsis_installer attrs: shortcuts_enabled_default (True),
shortcuts_start_menu_default (True), shortcuts_desktop_default (False) and
start_menu_folder (default <vendor_path or vendor>\<product_path>, relative
to the Programs folder).
When any component has shortcuts, a built-in Shortcuts options page is shown after the files were installed (before the Finish page). Its options can also be set on the command line, and are persisted:
| Key | Meaning |
|---|---|
shortcuts.enabled |
Master toggle, also governing path shortcuts. |
shortcuts.start_menu |
Create Start Menu shortcuts. |
shortcuts.start_menu_folder |
The Start Menu folder, e.g. /O:shortcuts.start_menu_folder=Custom\Folder. |
shortcuts.desktop |
Create Desktop shortcuts. |
The page is skipped when none of the installed components has shortcuts. In a silent install the shortcuts are created at the end of the installation.
The uninstaller removes a shortcut only if it still points into the installation directory, then removes the Start Menu folders it created if they are empty. Shortcuts the user repointed are kept (with a warning in the log).
Use nsis_symbol to declare an API and nsis_test_harness to build a standalone
test executable without writing JSON. Parameters use direction:name[:type],
for example ["in:count:int", "in:enabled:bool", "out:result:string"].
Supported types are string (default), signed 32-bit int, and bool, and list (an nsArray in NSIS, a Python list[str]).
The Python Harness validates inputs, converts outputs to their declared types,
captures stdout/stderr, checks that all 20 NSIS registers are preserved and the
stack is balanced, and can assert the NSIS error flag (expect_errors).
See the testing framework guide for Bazel definitions, typed Python assertions, installer/uninstaller support, and runnable examples. These unit harnesses are separate from the end-to-end installer tests.
Plugins beyond the ones in the NSIS distribution are declared with
nsis_plugin and listed in the plugins attribute of nsis_installer (and of
nsis_test_harness). Their DLLs and headers are added with !addplugindir
and !addincludedir before any other script content, so scripts can call
plugin_name::Function directly. Plugins are only embedded in an installer
when its script calls them.
load("@rules_nsis//nsis:defs.bzl", "nsis_plugin", "nsis_installer")
nsis_plugin(
name = "inetc",
plugin_name = "inetc", # defaults to `name`
x86_unicode = "Plugins/x86-unicode/inetc.dll",
amd64_unicode = "Plugins/amd64-unicode/inetc.dll",
includes = ["Include/inetc.nsh"], # optional headers
license = "Docs/inetc/License.txt", # mandatory
)
nsis_installer(
name = "installer",
plugins = [":inetc"],
...
)- Installers are Unicode, so only
x86_unicodeandamd64_unicodebuilds are taken; at least one is required. Each DLL must be named<plugin_name>.dllbecause makensis takes the command prefix from the file name. - If two plugins share a
plugin_name, makensis fails when the script calls it. - The licenses of an installer's plugins are in its
plugin_licensesoutput group.
nsis_plugin_archive fetches an archive with the usual layout
(Plugins/x86-unicode, Plugins/amd64-unicode or Plugins/x64-unicode, and
Include/*.nsh) and declares @<name>//:plugin:
nsis_plugin_archive = use_repo_rule("@rules_nsis//nsis:repositories.bzl", "nsis_plugin_archive")
nsis_plugin_archive(
name = "nsis_plugin_inetc",
plugin_name = "inetc",
urls = ["https://example.com/inetc.zip"],
sha256 = "...",
license = "Docs/inetc/License.txt",
)To fix a plugin, build it from its sources instead: patches (with
patch_strip, default 1) are applied to the extracted archive, and with
source_dir the .c files in that folder are compiled into both Unicode DLLs
with Zig. Like the plugins shipped with NSIS, they are linked without a C
runtime (entry point DllMain, importing only kernel32 and user32). copts
adds compiler flags, including preprocessor definitions such as -DNAME.
nsis_plugin_archive(
name = "nsis_plugin_inetc",
...
patches = ["//third_party:inetc-fix.patch"], # a git diff of the archive
source_dir = "Contrib/inetc",
copts = ["-DINETC_FEATURE"],
)For other layouts, use http_archive with a build_file_content that calls
nsis_plugin.
Every installer can use nsArray
1.1.1.7 by Stuart "Afrow UK" Welch (zlib-style license), which the bundled
includes use. It is downloaded from the NSIS wiki, pinned by sha256, and built
from source with a patch that fixes a heap overflow in nsArray::Split
(nsis/plugins/patches). It is built with -DARRAY_COPY and
-DARRAY_TOSTRING, so Array_Copy and Array_ToString from Array.nsh are
available. Keep its
license notice, from the plugin_licenses output group, when you distribute
an installer that embeds it.
EnVar (zlib-style license) is
bundled with every installer and test harness. It is downloaded from the NSIS
wiki, pinned by sha256, and used by add_to_path (EnvPath.nsh). Its license
is included in the plugin_licenses output group.
- Unicode
- Uninstaller file name:
uninstaller_name(defaultUninstall.exe), also used forUninstallString,QuietUninstallStringandDisplayIcon. - Writes to Windows Registry
Software\{{.Product}}orSoftware\{{.Vendor}}\{{.Product}}depending on what values are provided. Writes the values:- InstallDir
- Version
- When a previous install exists, a new install without
/D=installs into itsInstallDir./D=, or aPreInithook that changes$INSTDIR, takes precedence. Custom NSIS code can use${GetProductRegistry},${UpdateProductRegistry}and${RemoveProductRegistry}fromProduct.nshfor this key. - Adds uninstaller details to
Software\Microsoft\Windows\CurrentVersion\Uninstall\{{.Id}}writes to the same package path as above. Writes to subkeys:- DisplayName
- DisplayVersion
- Publisher
- UninstallString
- NoRepair = 1 (Repair not supported)
- NoModify = 1 (Modify not supported)
- DisplayIcon
- Writes to
32or64registry depending on arch selected. - Asserts that the installer is being run on the correct architecture based on provided arch.
- By default will allow 32bit installers to be installed on the 64bit system of
the same instruction set (
allow_32bit_on_64bit):x86_32onx86_64andarm32onarm64. Cross-ISA hosts (x86_32onarm32/arm64,arm32onx86_32/x86_64) are always rejected. Disabling the flag requires an exact architecture match. - Uses MUI for the UI.
- Logs to the details view, and to StdOut if run from a console.
log_levelselectsnone(disabled),debug,info(default),warnorerror. - The shell context (
SetShellVarContextand the HKLM/HKCU choice) defaults to the execution level. It is applied before thepre_init/pre_uninithooks and re-applied after them, so a hook may switch it withUpdateShellContextToAdmin/UpdateShellContextToCurrent. - Ensures only one installer is running using a mutex.
- Uninstalls previous installs when run.
- Installs and updates windows services using
sc.exe- Will always attempt to stop the service, waiting up to 30 seconds, before component section runs.
- On uninstall, stops the service and waits up to 30 seconds for it to be deleted.
- All component files are updated before the service is updated or created.
- Directory (tree artifact) sources are uninstalled file by file, then the empty directories are removed bottom-up without recursion, so files the user added are kept.
- When
/TESTID={{.TestId}}is passed, will append TestId to the registry keys it uses. This is to handle race conditions while testing installers. - If version is not provided, will default to
0.0.0.0. add_to_path = Trueon a component adds its install folder ($INSTDIRplusdirectory) toPATHand removes it on uninstall. The machinePATHis changed forexecution_level = "admin"installers, the user's otherwise.PATHis edited in place with the bundled EnVar plugin and never copied into an NSIS string, which would truncate it atNSIS_MAX_STRLENand corrupt it. Duplicates are not added. TheEnvPath_Add/EnvPath_Removemacros (EnvPath.nsh) are available to hooks.- EventLog keys written to
SYSTEM\CurrentControlSet\Services\EventLog\Application\{{.Id}}underHKLM(always, since the Event Log service only readsHKLM). Using aneventlogcomponent in an installer whoseexecution_levelis notadminfails the build. Message file paths are stored asREG_EXPAND_SZ, so environment variables such as%SystemRoot%expand.
MoveFileFolder.nsh provides ${MoveFile} source destination and
${MoveFolder} source destination mask, plus their un. variants.
By default, an existing destination file is replaced only when the source is
newer; otherwise the redundant source is removed. Set $switch_overwrite to
1 to replace regardless of age. Replacements use Windows MoveFileExW without
deleting the destination first, and failed moves retain the source and report
the NSIS error flag with a detail-log message.
Replacing a read-only destination now fails, even with $switch_overwrite = 1;
unlike the previous delete-then-rename implementation, its read-only attribute
is not cleared. Each macro clears the error flag on entry, so check IfErrors
immediately after each call, not just after a sequence of calls.
Folder moves retain their merge/mask behavior: nonmatching files stay in the source. Processing stops on the first failure and skips subsequent empty-folder cleanup; files already moved are not rolled back. Failed empty-folder removals are reported instead of retried indefinitely. Moving onto the same normalized path is a no-op; moving a folder into its own descendant is rejected. These guards compare filesystem identities and resolve existing destination ancestors, including short-name and junction aliases, without conflating distinct case-sensitive names. Moves fail conservatively when identity/resolved-path queries are unavailable. A failed cross-volume move can leave a copied destination alongside the retained source; it is reported as an error, and folder processing stops rather than continuing to later files. Folder traversal checks Win32 enumeration failures and rejects cycles/repeated directory identities before creating output. Both logical and resolved destination ancestors, including mapped child directories, are checked against the source tree. Combined paths are length-checked before construction. Literal source and destination paths reject wildcards before normalization; folder masks still support wildcards.
MoveFileFolder.nsh provides ${BackupFile} "$INSTDIR\settings.ini" and
${BackupFolder} "$INSTDIR\data" (also ${un.BackupFile} and ${un.BackupFolder}).
They move, rather than copy, the source to an unused sibling name:
file - Backup.txt, then file - Backup (2).txt, and so on; folders use
folder - Backup, then folder - Backup (2). Files retain their final
extension, and folders retain their entire contents, including empty folders.
Existing files or folders are never overwritten, even with
$switch_overwrite = 1. Missing sources, wrong source types, and rename
failures are logged and set the NSIS error flag; check it with IfErrors.
- Stamp values will be substituted with their workspace avlues when built with stamping.
- If build or installer is not stamped, stamp templates will be substituted using
stamp_defaultsif provided, otherwise, will default to the empty string. - Vendor and Product can be stamped, but it is not recommended since it can
result in odd or broken behavior (however, its behavior is well defined below).
- Output file name will not include stamped information unless
stamp_defaultshas a value for it. Because information gets removed, it can lead to unintentional file name clashes. - If you need these fields to be configurable, or want to follow DRY (Don't Repeat Yourself), it is recommended to use variables or configurable attributes.
- Output file name will not include stamped information unless
Based on dependencies provided in each component, a dependency graph between components is created and then embedded in the installer. In the component selection screen the following behavior will be seen:
- When a component is selected, all of its dependencies (including transitive dependencies) will also be selected.
- When a component is unselected, the all of its dependencies (including
transitive dependencies) will be unselected, unless:
- They were selected manually.
- They are depended on by another component (either directly or transitively).
- When a component is unselected, all dependents (either direct or transitive) will be unselected (even if they were selected manually).