Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
test committed Jan 14, 2021
0 parents commit b105592
Show file tree
Hide file tree
Showing 9 changed files with 358 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
log.txt
microhome/
5 changes: 5 additions & 0 deletions execwrapper.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
#!/usr/bin/env sh
# TODO: make sure this is actually portable
set -x
reset
exec "$@"
8 changes: 8 additions & 0 deletions help/selfexec.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# Selfexec plugin
This plugin is meant to make the plugin development process a little more convenient by bindig "reload" functionality to a key.

The default binding is to `Ctrl-r`, which conflicts with `ToggleRuler`.

The current implementation depends on being able to run a sh script and the exec syscall. No application state is saved, but thel list of currently open files is passed to the new session. You must save any files you've changed before executing the command. The behaviour is as if the program crashed, but backup restoration is set to manual mode.

For further information please review the plugin source.
35 changes: 35 additions & 0 deletions nix/add-syscall.patch
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
diff -Naur a/internal/lua/lua.go b/internal/lua/lua.go
--- b/internal/lua/lua.go
+++ a/internal/lua/lua.go
@@ -18,6 +18,7 @@
"sync"
"time"
"unicode/utf8"
+ "syscall"

humanize "github.com/dustin/go-humanize"
lua "github.com/yuin/gopher-lua"
@@ -44,6 +45,8 @@
switch pkg {
case "fmt":
return importFmt()
+ case "syscall":
+ return importSyscall()
case "io":
return importIo()
case "io/ioutil", "ioutil":
@@ -104,6 +107,14 @@

return pkg
}
+
+func importSyscall() *lua.LTable {
+ pkg := L.NewTable()
+
+ L.SetField(pkg, "Exec", luar.New(L, syscall.Exec))
+
+ return pkg
+}

func importIo() *lua.LTable {
pkg := L.NewTable()
15 changes: 15 additions & 0 deletions nix/default.nix
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
let
o = self: super: {
micro = super.micro.overrideAttrs (old: {
patches = [ ./add-syscall.patch ];
});
};
p = import (import ./sources.nix).nixpkgs { overlays = [ o ]; };
in {
shell = p.mkShell {
name = "tooling-shell";
buildInputs = [ p.micro ];
};
inherit p;
inherit (p) micro;
}
11 changes: 11 additions & 0 deletions nix/run.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
#! /usr/bin/env bash
SCRIPTPATH="$( cd "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )" # https://stackoverflow.com/questions/4774054/reliable-way-for-a-bash-script-to-get-the-full-path-to-itself
export MICRO_CONFIG_HOME="$SCRIPTPATH"/../microhome

pushd -- "$SCRIPTPATH"/..
mkdir -p -- "$MICRO_CONFIG_HOME"/plug/selfexec
cp -r -- selfexec.lua execwrapper.sh help "$MICRO_CONFIG_HOME"/plug/selfexec
popd

# https://github.com/zyedidia/micro/issues/1990#issuecomment-760094426 Support installing plugins from a local directory
$(nix-build -v "$SCRIPTPATH"/default.nix -A p.micro --no-out-link)/bin/micro -debug "$@"
26 changes: 26 additions & 0 deletions nix/sources.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
"niv": {
"branch": "master",
"description": "Easy dependency management for Nix projects",
"homepage": "https://github.com/nmattia/niv",
"owner": "nmattia",
"repo": "niv",
"rev": "18b7314c13a6d0e82113a15c14e7a5f54286327d",
"sha256": "0b2xb99nn7ddysvgzncwa4vglv0j6c0l4bgxz9hl4i3gmrlq3r59",
"type": "tarball",
"url": "https://github.com/nmattia/niv/archive/18b7314c13a6d0e82113a15c14e7a5f54286327d.tar.gz",
"url_template": "https://github.com/<owner>/<repo>/archive/<rev>.tar.gz"
},
"nixpkgs": {
"branch": "nixos-unstable",
"description": "Nix Packages collection",
"homepage": "",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "257cbbcd3ab7bd96f5d24d50adc807de7c82e06d",
"sha256": "0g3n725kjk2fc9yn9rvdjwci4mrx58yrdgp3waby9ky3d5xhcaw4",
"type": "tarball",
"url": "https://github.com/NixOS/nixpkgs/archive/257cbbcd3ab7bd96f5d24d50adc807de7c82e06d.tar.gz",
"url_template": "https://github.com/<owner>/<repo>/archive/<rev>.tar.gz"
}
}
174 changes: 174 additions & 0 deletions nix/sources.nix
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
# This file has been generated by Niv.

let

#
# The fetchers. fetch_<type> fetches specs of type <type>.
#

fetch_file = pkgs: name: spec:
let
name' = sanitizeName name + "-src";
in
if spec.builtin or true then
builtins_fetchurl { inherit (spec) url sha256; name = name'; }
else
pkgs.fetchurl { inherit (spec) url sha256; name = name'; };

fetch_tarball = pkgs: name: spec:
let
name' = sanitizeName name + "-src";
in
if spec.builtin or true then
builtins_fetchTarball { name = name'; inherit (spec) url sha256; }
else
pkgs.fetchzip { name = name'; inherit (spec) url sha256; };

fetch_git = name: spec:
let
ref =
if spec ? ref then spec.ref else
if spec ? branch then "refs/heads/${spec.branch}" else
if spec ? tag then "refs/tags/${spec.tag}" else
abort "In git source '${name}': Please specify `ref`, `tag` or `branch`!";
in
builtins.fetchGit { url = spec.repo; inherit (spec) rev; inherit ref; };

fetch_local = spec: spec.path;

fetch_builtin-tarball = name: throw
''[${name}] The niv type "builtin-tarball" is deprecated. You should instead use `builtin = true`.
$ niv modify ${name} -a type=tarball -a builtin=true'';

fetch_builtin-url = name: throw
''[${name}] The niv type "builtin-url" will soon be deprecated. You should instead use `builtin = true`.
$ niv modify ${name} -a type=file -a builtin=true'';

#
# Various helpers
#

# https://github.com/NixOS/nixpkgs/pull/83241/files#diff-c6f540a4f3bfa4b0e8b6bafd4cd54e8bR695
sanitizeName = name:
(
concatMapStrings (s: if builtins.isList s then "-" else s)
(
builtins.split "[^[:alnum:]+._?=-]+"
((x: builtins.elemAt (builtins.match "\\.*(.*)" x) 0) name)
)
);

# The set of packages used when specs are fetched using non-builtins.
mkPkgs = sources: system:
let
sourcesNixpkgs =
import (builtins_fetchTarball { inherit (sources.nixpkgs) url sha256; }) { inherit system; };
hasNixpkgsPath = builtins.any (x: x.prefix == "nixpkgs") builtins.nixPath;
hasThisAsNixpkgsPath = <nixpkgs> == ./.;
in
if builtins.hasAttr "nixpkgs" sources
then sourcesNixpkgs
else if hasNixpkgsPath && ! hasThisAsNixpkgsPath then
import <nixpkgs> {}
else
abort
''
Please specify either <nixpkgs> (through -I or NIX_PATH=nixpkgs=...) or
add a package called "nixpkgs" to your sources.json.
'';

# The actual fetching function.
fetch = pkgs: name: spec:

if ! builtins.hasAttr "type" spec then
abort "ERROR: niv spec ${name} does not have a 'type' attribute"
else if spec.type == "file" then fetch_file pkgs name spec
else if spec.type == "tarball" then fetch_tarball pkgs name spec
else if spec.type == "git" then fetch_git name spec
else if spec.type == "local" then fetch_local spec
else if spec.type == "builtin-tarball" then fetch_builtin-tarball name
else if spec.type == "builtin-url" then fetch_builtin-url name
else
abort "ERROR: niv spec ${name} has unknown type ${builtins.toJSON spec.type}";

# If the environment variable NIV_OVERRIDE_${name} is set, then use
# the path directly as opposed to the fetched source.
replace = name: drv:
let
saneName = stringAsChars (c: if isNull (builtins.match "[a-zA-Z0-9]" c) then "_" else c) name;
ersatz = builtins.getEnv "NIV_OVERRIDE_${saneName}";
in
if ersatz == "" then drv else
# this turns the string into an actual Nix path (for both absolute and
# relative paths)
if builtins.substring 0 1 ersatz == "/" then /. + ersatz else /. + builtins.getEnv "PWD" + "/${ersatz}";

# Ports of functions for older nix versions

# a Nix version of mapAttrs if the built-in doesn't exist
mapAttrs = builtins.mapAttrs or (
f: set: with builtins;
listToAttrs (map (attr: { name = attr; value = f attr set.${attr}; }) (attrNames set))
);

# https://github.com/NixOS/nixpkgs/blob/0258808f5744ca980b9a1f24fe0b1e6f0fecee9c/lib/lists.nix#L295
range = first: last: if first > last then [] else builtins.genList (n: first + n) (last - first + 1);

# https://github.com/NixOS/nixpkgs/blob/0258808f5744ca980b9a1f24fe0b1e6f0fecee9c/lib/strings.nix#L257
stringToCharacters = s: map (p: builtins.substring p 1 s) (range 0 (builtins.stringLength s - 1));

# https://github.com/NixOS/nixpkgs/blob/0258808f5744ca980b9a1f24fe0b1e6f0fecee9c/lib/strings.nix#L269
stringAsChars = f: s: concatStrings (map f (stringToCharacters s));
concatMapStrings = f: list: concatStrings (map f list);
concatStrings = builtins.concatStringsSep "";

# https://github.com/NixOS/nixpkgs/blob/8a9f58a375c401b96da862d969f66429def1d118/lib/attrsets.nix#L331
optionalAttrs = cond: as: if cond then as else {};

# fetchTarball version that is compatible between all the versions of Nix
builtins_fetchTarball = { url, name ? null, sha256 }@attrs:
let
inherit (builtins) lessThan nixVersion fetchTarball;
in
if lessThan nixVersion "1.12" then
fetchTarball ({ inherit url; } // (optionalAttrs (!isNull name) { inherit name; }))
else
fetchTarball attrs;

# fetchurl version that is compatible between all the versions of Nix
builtins_fetchurl = { url, name ? null, sha256 }@attrs:
let
inherit (builtins) lessThan nixVersion fetchurl;
in
if lessThan nixVersion "1.12" then
fetchurl ({ inherit url; } // (optionalAttrs (!isNull name) { inherit name; }))
else
fetchurl attrs;

# Create the final "sources" from the config
mkSources = config:
mapAttrs (
name: spec:
if builtins.hasAttr "outPath" spec
then abort
"The values in sources.json should not have an 'outPath' attribute"
else
spec // { outPath = replace name (fetch config.pkgs name spec); }
) config.sources;

# The "config" used by the fetchers
mkConfig =
{ sourcesFile ? if builtins.pathExists ./sources.json then ./sources.json else null
, sources ? if isNull sourcesFile then {} else builtins.fromJSON (builtins.readFile sourcesFile)
, system ? builtins.currentSystem
, pkgs ? mkPkgs sources system
}: rec {
# The sources, i.e. the attribute set of spec name to spec
inherit sources;

# The "pkgs" (evaluated nixpkgs) to use for e.g. non-builtin fetchers
inherit pkgs;
};

in
mkSources (mkConfig {}) // { __functor = _: settings: mkSources (mkConfig settings); }
82 changes: 82 additions & 0 deletions selfexec.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
-- TODO profile why loading is slow

local function lib()
local function mut_append2(table1, table2)
local len = #table1
for i = 1, #table2 do
table1[len + i] = table2[i]
end
end

local function mut_append(tab, val, ...)
if val == nil
then return tab
else
table.insert(tab, val)
return mut_append(tab, ...)
end
end

local function pop(tab)
local val = tab[#tab]
table.remove(tab)
return val
end

return { ["pop"] = pop, ["mut_append"] = mut_append, ["mut_append2"] = mut_append2 }
end
local lib = lib()

-- Functionality for making plugin development a little more convenient:
-- This provides a key binding to reload the editor.
local function selfexec()
local micro = import("micro")
local config = import("micro/config")
local os = import("os")
local syscall = import("syscall")

-- TODO nag upstream about whether there is a better way
local plugd = config.ConfigDir .. "/plug/selfexec"

local function selfexec()
-- Calling exec somehow messes up the teminal state.
-- we use a wrapper script that calls the `reset` command to fix the shell, and then execs its argv
local wrapper = plugd .. "/execwrapper.sh"

-- For some reason calling (this?) exec overwrites the argv0 meaning it points to the execme.sh
-- The workaround is to pass the entire old argv shifted by one, so the original executable is also
-- passed as an argument. E.g.:
-- [ "execwrapper.sh", "-debug", "whatever.file" ] -> [ "execwrapper.sh", "micro", "-debug", "whatever,file" ]
-- If we were directly exec-ing outselves, we wouldn't need to worry about argv[0].
local args = { wrapper } -- This first value could be anything?
lib.mut_append2(args, os.Args)

-- Due to the fact that exec is an unclean shutdown method, micro will nag about restoring backups,
-- even if we saved the document properly. We turn on manual backup handling after a reload to work around this.
-- TODO can we do a clean "shutdown" before we call exec?
if not config.GetGlobalOption("permbackup") then
-- the only state we keep is open files and we assume the last argument is the only opened file
-- TODO nag upstream about enumerating / accessing buffers -- https://github.com/zyedidia/micro/issues/1993 Lua: methods to access open buffers
-- TODO multiple files, maybe serialized layout? / other stuff -
-- going full xmonad here...how much state can we reasonably serialize?
local file = lib.pop(args)
lib.mut_append(args, "-permbackup", "true", file) --TODO well really I should just rewrit this as "insert after flags position" no?
end

micro.Log("Attempting reload with args.."); micro.Log(args)
syscall.Exec(wrapper, args, os.Environ())
end

local function doBind()
config.TryBindKey("Ctrl-r", "lua:selfexec._selfexec", true)
end

local function init()
micro.Log("Loaded with args..."); micro.Log(os.Args)
doBind()
end

init()
return { ["selfexec"] = selfexec }
end
_selfexec = selfexec().selfexec --TODO get upstream to support this -- https://github.com/zyedidia/micro/issues/1989 Accept arbitrary lua expression in LuaAction / "lua:" binding target

0 comments on commit b105592

Please sign in to comment.