Git Product home page Git Product logo

wasm-git's Introduction

Wasm-git

(Wasm should be pronounced like awesome starting with a W ).

GIT for nodejs and the browser using libgit2 compiled to WebAssembly with Emscripten.

Demo in the browser

A simple demo in the browser can be found at:

https://wasm-git.petersalomonsen.com/

Please do not abuse, this is open for you to test and see the proof of concept

The sources for the demo can be found in the githttpserver project, which is a simple git server deployable to kubernetes. Showing basic operations like cloning, edit files, add and commit, push and pull.

Example WebWorker with pre built binaries

For running in the browser you should have your git interaction code in a webworker. This is because of the use of synchronous http requests and long running operations that would block if running on the main thread.

Here's an example of a simple webworker that uses pre-built binaries from https://unpkg.com/[email protected]/

var Module = {
    locateFile: function(s) {
      return 'https://unpkg.com/[email protected]/' + s;
    }
};

importScripts('https://unpkg.com/[email protected]/lg2.js');

Module.onRuntimeInitialized = () => {
    const lg = Module;

    FS.mkdir('/working');
    FS.mount(MEMFS, { }, '/working');
    FS.chdir('/working');    

    FS.writeFile('/home/web_user/.gitconfig', '[user]\n' +
                'name = Test User\n' +
                'email = [email protected]');

    // clone a local git repository and make some commits

    lg.callMain(['clone',`http://localhost:5000/test.git`, 'testrepo']);

    FS.readdir('testrepo');
}

You'll start the worker from your html with the tag:

<script>new Worker('yourworker.js')</script>;

The example above expects to find a git repository at http://localhost:5000/test.git. If you want to clone from github you'd need a proxy running locally because of CORS restrictions that would prevent you accessing github directly. For testing you can use the proxy found in examples/webserverwithgithubproxy.js

Use in Browser without a WebWorker

A webworker is more performant but for cases where you really need to work in the browser, the http requests must be asynchronous and not synchronous as in the default builds.

If you use the emscriptenbuilds/build.sh you can build async versions with:

./build.sh Release-async

and

./build.sh Debug-async

To use the async wasm-git build you need to load lg2.js using a <script> tag in HTML, and set up a method to wait for initialisation of the lg2 module. For example, your index.html can include the following, and set up a promise for your JavaScript implementation to await:

<!DOCTYPE html>
<html lang="en">
<head>
	<script src='/build/lg2.js'></script>
  
	<script>
	window.lg2Ready = false;
	window.lg2 = Module;
	window.lg2ReadyPromise = new Promise((resolve) => {
		Module.onRuntimeInitialized = () => {
			window.lg2Ready = true;
			resolve(true);
		};
	});
	</script>

<script defer src='/build/bundle.js'></script>
</head>

<body>
</body>
</html>

In your bundle, you will have JavaScript to await window.lg2ReadyPromise and can then use await callMain() to invoke libgit2 features exposed by wasm-git. Notice you MUST use await on every callMain() which interacts with a remote repository (e.g. 'clone', 'push' and so on). Example:

async function initApp() {
	await window.lg2ReadyPromise;
	await test();
}

async function test() {
	const lg = window.lg2;
    const FS = lg.FS;

    const lg = Module;

    FS.mkdir('/working');
    FS.mount(MEMFS, { }, '/working');
    FS.chdir('/working');    

    FS.writeFile('/home/web_user/.gitconfig', '[user]\n' +
                'name = Test User\n' +
                'email = [email protected]');

    // clone a local git repository and make some commits

    await lg.callMain(['clone',`http://localhost:5000/test.git`, 'testrepo']);

    FS.readdir('testrepo');
}

Note that the compiled output is about twice the size for non-async builds, and that git operations will take place on the main thread which can affect reponsiveness of your web UI.

See below for more details on building using build.sh.

Use from nodejs with pre built binaries

You may install the npm package containing the binaries:

npm install wasm-git

example source code for cloning a repository from github:

const lg = require('./node_modules/wasm-git/lg2.js');

lg.onRuntimeInitialized = () => {
    const FS = lg.FS;
    const MEMFS = FS.filesystems.MEMFS;

    FS.mkdir('/working');
    FS.mount(MEMFS, { }, '/working');
    FS.chdir('/working');    

    FS.writeFile('/home/web_user/.gitconfig', '[user]\n' +
                'name = Test User\n' +
                'email = [email protected]');
    
    // clone a repository from github
    lg.callMain(['clone','https://github.com/torch2424/made-with-webassembly.git', 'made-with-webassembly']);
    FS.readdir('made-with-webassembly');
}

Building

IMPORTANT: This depends on the following mmap fixes for emscripten:

for using with NODEFS you'll also need emscripten-core/emscripten#10669

All of these pull requests are merged to emscripten master as of 2020-03-29.

See .github/workflows/main.yml for a full build and test pipeline including installing emscripten.

Run setup.sh first to download libgit2 and apply patches.

Given you have installed and activated emscripten, you can use the script in emscriptenbuild/build.sh to configure and build, and you'll find the resulting lg2.js / lg2.wasm under the generated emscriptenbuild/examples folder.

An example of interacting with libgit2 from nodejs can be found in examples/example_node.js.

An example for the browser (using webworkers) can be found in examples/example_webworker.js. You can start a webserver for this by running the examples/webserverwithgithubproxy.js script, which will launch a http server at http://localhost:5000 with a proxy to github. Proxy instead of direct calls is needed because of CORS restrictions in a browser environment.

wasm-git's People

Contributors

alexzuza avatar dependabot[bot] avatar happybeing avatar happyfacade avatar petersalomonsen avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

wasm-git's Issues

How to do a git clone to be used from memfs + questions about global variables

I am trying to expose wasm-git as a raw interface similar to https://isomorphic-git.org/en/

I have this file:

https://github.com/nikitavoloboev/inlang/blob/libgit2/source-code/git-sdk/src/api/index.ts#L4

Trying to base it off https://github.com/petersalomonsen/javascriptmusic/blob/master/wasmaudioworklet/wasmgit/wasmgitworker.js

I get lots of TS issues as it doesn't know what FS means, it's a global variable, not sure where is it defined?

image

In the end I would essentially do a call similar to

	await raw.clone({
		fs: args.fs,
		http,
		dir: "/",
		corsProxy: clientSideEnv.VITE_GIT_REQUEST_PROXY_PATH,
		url: `https://${host}/${owner}/${repository}`,
	})

But with exposed wasm-git.

Also I see lg.callMain(['clone',http://localhost:5000/test.git`, 'testrepo']);` used in example but it doesn't seem to accept as argument a file system, is this possible to pass?

I essentially want to do a git clone with wasm-git to be used from https://www.npmjs.com/package/memfs

For FS issue, I at first thought I should do import FS = require('fs'); but wasmgitworker.js didn't have it so not sure.

Thanks for any help on this. ♥️

What does `if (mode === 0o100000 > 0)` mean?

See

if (mode === 0o100000 > 0) {

I've found this in https://github.com/kiegroup/kie-tools/blob/main/.github/supporting-files/publish_emscripten_fs/post.js

I have no idea why that is not a if (mode === true) instead, or if it's a typo, or if it's ever false in general ... proof:

var mode = 0o100000;
if (mode === 0o100000 > 0)
  console.log('this would never be seen');

var mode = 0;
if (mode === 0o100000 > 0)
  console.log('this would never be seen');

var mode = true;
if (mode === 0o100000 > 0)
  console.log('finally a log');

As precedence looks like not intentional, or the check against true not present, what is the purpose of this patch?

Thank you for clarifying, dropping that, or fixing it in a way that makes sense, because 0o100000 > 0 is always true, so it's really not clear what's going on with that if statement.

Advice for a Rust/Wasm Git project

I'm building a GitHub like static web app, a p2p Git Portal which will run from static hosting or peer-to-peer storage (so no server side code) and hoping you can give me some advice on whether I can do what I need with wasm-git.

I have a proof-of-concept in Go/Wasm but need to replace Go with a better wasm source and long term will aim for Rust/Wasm. I'll need git features (so wasm-git) and plan to add support for issues, PRs using git objects (the approach used by the Go library git-bug as in my demo).

I'm novice in all these areas so unsure how to do this and wondering if this a good approach and how to go about:

  • using wasm-git from Rust rather than JS
  • replacing the filesystem with one of my choosing (so I can use p2p storage either via JS or wasm bindings in the browser)
  • using Rust to implement issues, comments, PRs etc within the .git storage, along with general 'business logic' for a p2p Git Portal (like GitHub)

It all looks possible but I'm not sure how hard it will be to get there, and if I have the time and skill to attempt it. I could carry on with the Go/Wasm, but Go isn't good for security or reliability, is too slow and has a 12MB runtime. You can see the first demo of the portal which has basic git functionality plus create/view issues (no UI for creation yet) here: http://gitch.happybeing.com It's not a million miles away from the features of your own demo, but with added issues!

Any tips or warnings etc would be very much appreciated. I've had a talk with the author of gitoxide a naive Rust implementation of git primitives, but there's not much functionality there yet so I'm looking for an alternative way of obtaining the core git functionality so I can focus on the additional features.

No output when calling `callMain` with args

This project is really cool. Thanks for all your work!

I have followed some related issues (#80) to capture the output, which working fine in some simple cases.

But it seems not work if I sending some args together.

// OK
lg.callMain(["log"])
// NO OUTPUT
lg.callMain(["log", "-p"])

Full snippet:

const lg = require('./node_modules/wasm-git/lg2.js');
let stdout;


lg["print"] = function (text) {
    console.log(text);
}

lg["printErr"] = function (text) {
    console.error(text);
}

lg.onRuntimeInitialized = () => {
    const FS = lg.FS;
    const NODEFS = FS.filesystems.NODEFS;

    FS.mkdir('/working');
    FS.mount(NODEFS, {root: '..'}, '/working');
    FS.chdir('/working');

    const gitConfigContent = '[user]\n' +
        'name = Test User\n' +
        'email = [email protected]\n' +
        '[safe]\ndirectory = *\n';

    FS.writeFile('/home/web_user/.gitconfig', gitConfigContent, (err) => {
        if (err) throw err;
        console.log('File has been saved!');
    });

    console.log(FS.readdir('.'));

    // OK
    lg.callMain(["log"])
    // NO OUTPUT
    lg.callMain(["log", "-p"])
};

How to access result of "git status"?

Hey, I'm liking this library more and more, it seems it's much more performant already than isomorphic-git.
Although It's currently lacking documentation I will gladly write some if this library turns out to be performant enough for our product.

I'm following the webworker example and I'm calling lg.callMain(['status']) but it doesn't return anything other than logging to the console so I'm wondering how I can check the result of git status programatically?

`lg.callMain(['checkout', '--', 'a-deleted-file.txt'])` failed

version: 0.0.6

I'm using wasm-git with NODEFS in a worker in a electron render process. git checkout -- a-deleted-file.txt will cause a crash when:

Step 0: mount Emscripten FS with NODEFS on a physical directory -> FS.chdir -> lg.callMain(['init', '.']) -> lg.callMain(['status'])

Step 1: use Noejs FS API(outside of worker) to create a file in the physicial directory, and lg.callMain(['add', '.']) -> lg.callMain(['commit', '-m', 'commit message']) -> lg.callMain(['status'])

Step 2: use Nodejs FS API(outside of worker) to delete the file in the physicial direcotry, and lg.callMain(['add', '.']) -> lg.callMain(['status']) -> lg.callMain(['checkout', '--', 'the-deleted-file.txt']) -> lg.callMain(['status']). The deleted file will be restored in physicial direcotry successfully.

Step 3: repeat Step 2. And cause crash when lg.callMain(['checkout', '--', 'the-deleted-file.txt'])

图片

Am I using checkout feature in a wrong way? In real git, if we want to restore a deleted file in working tree, we should use git checkout HEAD -- the-deleted-file.txt, but wasm-git seems to do not support lg.callMain(['checkout', 'HEAD', '--', 'the-deleted-file.txt']), so I just omit 'HEAD'.

How to use wasm-git with different version of libgit2?

I need to do a sparse clone with libgit2 and the current wasm-git doesn't expose this feature.

However there is this PR that passes tests but sadly not yet merged into main tree of libgit2.

I need the sparse clone feature and I need to run libgit2 with wasm so I thought I build the libgit2 from the pr and expose it through wasm-git. One thing I am not sure about is where would I start with this.

I thought I should look into the build.sh file but I didn't see where in there the chosen libgit2 version is picked. I assume somewhere a clone happens, perhaps I can change that clone to point to clone the PR instead and then leave the other instructions as they are?

Thank you for any help.

travis.yml

The README says "See .travis.yml for a full build and test pipeline including installing emscripten." This file does not seem to exist.

Optimize wasm file

Stripping the debug symbols and optimizing with wasm-opt cuts lg2.wasm down from 6.3Mb to 1.1Mb, and seems to execute a little faster (only minimally tested). May want to see if you can do the same thing for the packaged version.

wasm-opt --strip-debug -O3 emscriptenbuild/libgit2/examples/lg2.wasm -o emscriptenbuild/libgit2/examples/lg2-stripped.wasm

Failed To Init with Template

Hello! This technically isn't an issue, which is why I'll close the issue immediately after opening it. But I wanted to check to see if you had a pointer. If you've got no idea about this error don't worry about it.

So, I've gotten pretty far porting this library to Deno (thanks to deno's node-compatibilty mode).

However, when I clone a repository it makes all the git folders, creates an empty description file but then fails immediately after

ERROR 2: failed to initialize repository with template 'description': Invalid argument

Which originates from here inside the repo_write_template() function in libgit2.

I don't know why 'description' is being passed in to a template function (I'm not familiar with git's definition of a template), and thats made me a bit stumped as to what part of the javascript could be causing this failure, so I figured I should see if you ever dealt with something similar.

Trying to run it

I'm on MacOS Ventura, unfortunately couldn't build it.

So I used npm i wasm-git in a temporary folder and copied over lg2.js and lg2.wasm over the files here.

Then I executed:

node webserverwithgithubproxy.js

Although, in Chrome at http://localhost:5000 see error:

Uncaught (in promise) ErrnoError {node: undefined, errno: 44, message: 'FS error', stack: '<generic error, no stack>', setErrno: ƒ}

Here's the screenshot:

image

What I did wrong? Any ideas?

Add TypeScript types to final bundle

I would love to get autocomplete on the exposed wasm-git module.

Not sure how to achieve it best though. I thought perhaps wasm-git npm package exposes one WasmGit TypeScript type (not sure on name) and then in code you can do:

;(async () => {
  const libgit: WasmGit = await libgitPromise

This way libgit is fully typed at this point. Can type libgit. and get completion for callMain. Get completions for callMain commands too.

To achieve this I guess we can parse C code functions that are defined in commands array and create type definitions? Or maybe there's a nicer way.

`could not remove directory` error during branch removal

Hello, @petersalomonsen,

First of all, I’m really impressed by the wasm-git library, good job!

I recently encountered an issue while working with the library, and I’m not sure how to handle it. It occurs during the removal of branches. When calling:

lg.callAndCaptureOutput(['branch', '-d', BRANCH_NAME]);
await syncFS();
lg.callAndCaptureOutput(['push', ':refs/heads/BRANCH_NAME']);
await syncFS();

I receive the following error from time to time:

Error branch move [-1] - could not remove directory '/[REPO]/.git/refs/heads/[BRANCH_NAME]': still present.

Retrying the operation often helps but not always.

Have you encountered maybe such an error?

Emulate git cli in browser

Can I use this library to emulate git cli in browser, e.g. to act as a git playground?

So that the user may git init, run git commands, etc.

How difficult does that appear to implement (in git-related part)?

How to use in Deno?

I tried:

// debug.ts
import lg from "npm:wasm-git/lg2.js";

lg.onRuntimeInitialized = () => {
  const FS = lg.FS;
  const MEMFS = FS.filesystems.MEMFS;

  FS.mkdir("/working");
  FS.mount(MEMFS, {}, "/working");
  FS.chdir("/working");

  FS.writeFile(
    "/home/web_user/.gitconfig",
    "[user]\n" +
      "name = Test User\n" +
      "email = [email protected]",
  );

  // clone a repository from github
  lg.callMain([
    "clone",
    "https://github.com/torch2424/made-with-webassembly.git",
    "clonedtest",
  ]);

  FS.chdir("clonedtest");
  console.log(FS.readdir("."));
  lg.callMain(["log"]);
};

It outputs an error:

$ time deno run -A debug.ts
[ ".", "..", ".git" ]
Could not find repository HEAD [-1] - reference 'refs/heads/master' not found

real    0m0.093s
user    0m0.130s
sys     0m0.073s

Rebuilding on MacOS for development

Let's say I want to create new commands.

I follow these steps for the initial build:

npm install
sh setup.sh
git clone https://github.com/emscripten-core/emsdk.git
cd emsdk
./emsdk install latest
./emsdk activate latest
cd ..
source ./emsdk/emsdk_env.sh
cd emscriptenbuild
./build.sh Release

Is it correct? Should I use Release?

Also, on changes, should I re-run ./build.sh Release to get a new build?

Bad news: early EOF

I have cloned the githttpserver repository and when running it locally I still get CORS errors, which I mitigated for now by running Chrome with disable-web-security flag.

After that, when trying to clone any public repository I get the error "Bad news: early EOF", which after a quick google search usually indicates a too large repository, but that cannot be the case because I am successful in cloning them e.g. with isomorphic-git.

So I'm wondering if there's anything that I'm missing here?

wasm-git looks super promising and I'm really curious how it compares in performance to isomorphic-git

Clone arguments `--depth 1` not working with `lg.callMain(['clone', url, dir, '--depth', '1'])`

Currently trying to experiment the performance of wasm-git for not-so-small Git repositories, but using --depth 1 on a clone call doesn't seem to have any effect. Any idea what could be happening?

What I did was I modified the githttpserver to not add an Authorization header to HTTP requests and used Isomorphic Git's CORS proxy to bypass CORS restrictions to GitHub. So from my localhost, I try to download any fairly-sized GitHub repository, and it takes forever, even with --depth 1.

Let me know if I can help fixing this!

Does wasm-git support custom File System?

Background

I know we can use four type file system with emscripten, MEMFS / NODEFS / IDBFS / WORKERFS / PROXYFS.
But I have a cross-process File System(Compatible Node.js FS) for Browser, it can share multiple workers.

Question

can I provider my custom File System for wasm-git?

missing files for setup.sh

in setup.sh: where should: libgit2patchedfiles/* come from? Is there another repo or step required ?

Also libgit2/src/transports/http.c does not seem to exist in the tar file that the script downloads?

Git config

wasm-git always commits with name Me and e-mail [email protected] when using inside web-worker.
I tried creating /home/web_user/.gitconfig

 FS.writeFile('/home/web_user/.gitconfig', '[user]\n' +
                        `name = ${event.data.name}\n` +
                        `email = ${event.data.email}`);

and creating the config locally:

lg.callMain(['config', 'user.name', event.data.name]);
lg.callMain(['config', 'user.email', event.data.email]);

Both doesn't work.
The complete script for the web-worker:

var Module = {
        locateFile: s => `https://unpkg.com/[email protected]/${s}`
}

importScripts('https://unpkg.com/[email protected]/lg2.js');

Module.onRuntimeInitialized = () => {
        const lg = Module;
        FS.mkdir('/working');
        FS.mount(MEMFS, { }, '/working');

        const printError = err;
        let processStep;
        let terminate;
        err = obj => {
                printError(obj);
                terminate = true;
                postMessage({state: 'terminated', error: obj, processStep});
        };
        onmessage = (event) => {
                FS.writeFile('/home/web_user/.gitconfig', '[user]\n' +
                        `name = ${event.data.name}\n` +
                        `email = ${event.data.email}`);

                processStep = 'clone'
                lg.callMain([processStep, event.data.url, event.data.repo]);
                if (terminate)
                        return;
                FS.chdir(event.data.repo);

                processStep = 'checkout';
                lg.callMain([processStep, event.data.sourceBranch]);
                if (terminate)
                        return;
                processStep = 'checkout';
                lg.callMain([processStep, event.data.targetBranch]);
                if (terminate)
                        return;
                processStep = 'merge';
                lg.callMain([processStep, event.data.sourceBranch]);
                if (terminate)
                        return;
                processStep = 'push';
                lg.callMain([processStep]);
                if (terminate)
                        return;
                postMessage({state: 'merged'});
        };
        postMessage({state: 'ready'});
}

Mounting filesystems

It seems there's only an in-memory filesystem included with wasm-git (totally makes sense) but if I'm not completely mistaken it also looks like this can quite easily be replaced simply by mounting a filesystem at a given path? Digging through the FS object I see this:

Screenshot 2020-02-26 at 19 13 49

Is there any documentation you can point to on how to implement this interface, and is this all that's needed to plug in a different kind of filesystem?

What I'd like to do is actually write to disk, not memory, when my application is running on a local machine (in Electron, hence #2, but I can do this in Node just as well) but when it's running in a browser I obviously would use an in-memory filesystem. I don't want to just dump one big blob, I'd actually like to write proper files that could be used with a regular git client outside of my app as well.

Add all files to staging

Hi, I had a doubt on how could i simulate git add --all behaviour with this module. Git add with libgit2 does not suppport --all argument. Any suggestions on how i could do it?

Not compatible with Electron?

Hi – cool project!

I was just trying out your node example in an Electron project, but get the following error:

/Users/mstade/dev/cjm/journeyman/node_modules/wasm-git/lg2.js:1 exception thrown: Error: The V8 platform used by this instance of Node does not support creating Workers,Error: The V8 platform used by this instance of Node does not support creating Workers
    at new Worker (internal/worker.js:100:21)
    at Object.emscriptenhttpconnect (/Users/mstade/dev/cjm/journeyman/node_modules/wasm-git/lg2.js:1:127240)
    at 72457 (/Users/mstade/dev/cjm/journeyman/node_modules/wasm-git/lg2.js:1:14890)
    at _emscripten_asm_const_iii (/Users/mstade/dev/cjm/journeyman/node_modules/wasm-git/lg2.js:1:15413)
    at wasm-function[2224]:79
    at wasm-function[2145]:58
    at wasm-function[348]:8
    at wasm-function[2160]:180
    at wasm-function[2141]:233
    at wasm-function[559]:312

I am however able to run the example just using Node, so this seems to be distinctly an issue with Electron. I'll try to figure this out, but any pointers or suggestions you may have are more than welcome!

Is it possible to push to a github repo?

Let's say we cloned a (public) github repository.

Is there a way to push there?

The only problem I see is credentials (reading can be public, writing - cannot). Any other issues?

For credentials, let's say, we're using our proxy (we have to do so anyway due to same-origin policy).
Maybe we can use a Github App to get permissions for a repo, and then add these credentials to push requests (basically add auth tokens to requests)?

Question: Use in a VSCode extension

It can be a pain for non-techies to install git on non-persistant public (Windows) computers and it would be great to be able to use VSCode to properly interact with Github without local git. It would also allow for some cool stuff with the new vscode.dev, given you can now dev on local folders.

Is there any fundamental reason why an extension couldn't use this project to provide the basic features of interaction with Github (or any git...)?

Failing to build wasm-git

Get below after getting deps and trying to run test suite:

~/clones/wasm-git master*
❯ npm i

up to date, audited 185 packages in 692ms

24 packages are looking for funding
  run `npm fund` for details

7 vulnerabilities (2 moderate, 4 high, 1 critical)

To address all issues, run:
  npm audit fix

Run `npm audit` for details.

~/clones/wasm-git master*
❯ npm run test

> [email protected] test
> mocha test/**/*.spec.js



  git checkout
    1) "before each" hook for "should discard changes to a path"
(node:42368) PromiseRejectionHandledWarning: Promise rejection was handled asynchronously (rejection id: 1)
(Use `node --trace-warnings ...` to show where the warning was created)

  conflicts
    2) "before each" hook for "should create 1 bare and 2 clones and create/resolve conflicts"

  git fetch
    3) "before each" hook for "should create 1 bare and 2 clones and fetch changes"

  nodefs
    4) should clone using nodefs

  git revert
    5) "before each" hook for "should revert commit"


  0 passing (6ms)
  5 failing

  1) git checkout
       "before each" hook for "should discard changes to a path":
     Error: Cannot find module './lg2.js'
Require stack:
- /Users/nikiv/clones/wasm-git/test/common.js
- /Users/nikiv/clones/wasm-git/test/checkout.spec.js
      at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
      at Function.Module._load (node:internal/modules/cjs/loader:778:27)
      at Module.require (node:internal/modules/cjs/loader:999:19)
      at require (node:internal/modules/cjs/helpers:102:18)
      at module.exports.lgPromise (test/common.js:3:20)
      at new Promise (<anonymous>)
      at Object.<anonymous> (test/common.js:2:16)
      at Module._compile (node:internal/modules/cjs/loader:1099:14)
      at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
      at Module.load (node:internal/modules/cjs/loader:975:32)
      at Function.Module._load (node:internal/modules/cjs/loader:822:12)
      at Module.require (node:internal/modules/cjs/loader:999:19)
      at require (node:internal/modules/cjs/helpers:102:18)
      at Object.<anonymous> (test/checkout.spec.js:1:19)
      at Module._compile (node:internal/modules/cjs/loader:1099:14)
      at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
      at Module.load (node:internal/modules/cjs/loader:975:32)
      at Function.Module._load (node:internal/modules/cjs/loader:822:12)
      at ModuleWrap.<anonymous> (node:internal/modules/esm/translators:170:29)
      at ModuleJob.run (node:internal/modules/esm/module_job:198:25)
      at async Promise.all (index 0)
      at async ESMLoader.import (node:internal/modules/esm/loader:409:24)
      at async importModuleDynamicallyWrapper (node:internal/vm/module:437:15)

  2) conflicts
       "before each" hook for "should create 1 bare and 2 clones and create/resolve conflicts":
     Error: Cannot find module './lg2.js'
Require stack:
- /Users/nikiv/clones/wasm-git/test/common.js
- /Users/nikiv/clones/wasm-git/test/checkout.spec.js
      at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
      at Function.Module._load (node:internal/modules/cjs/loader:778:27)
      at Module.require (node:internal/modules/cjs/loader:999:19)
      at require (node:internal/modules/cjs/helpers:102:18)
      at module.exports.lgPromise (test/common.js:3:20)
      at new Promise (<anonymous>)
      at Object.<anonymous> (test/common.js:2:16)
      at Module._compile (node:internal/modules/cjs/loader:1099:14)
      at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
      at Module.load (node:internal/modules/cjs/loader:975:32)
      at Function.Module._load (node:internal/modules/cjs/loader:822:12)
      at Module.require (node:internal/modules/cjs/loader:999:19)
      at require (node:internal/modules/cjs/helpers:102:18)
      at Object.<anonymous> (test/checkout.spec.js:1:19)
      at Module._compile (node:internal/modules/cjs/loader:1099:14)
      at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
      at Module.load (node:internal/modules/cjs/loader:975:32)
      at Function.Module._load (node:internal/modules/cjs/loader:822:12)
      at ModuleWrap.<anonymous> (node:internal/modules/esm/translators:170:29)
      at ModuleJob.run (node:internal/modules/esm/module_job:198:25)
      at async Promise.all (index 0)
      at async ESMLoader.import (node:internal/modules/esm/loader:409:24)
      at async importModuleDynamicallyWrapper (node:internal/vm/module:437:15)

  3) git fetch
       "before each" hook for "should create 1 bare and 2 clones and fetch changes":
     Error: Cannot find module './lg2.js'
Require stack:
- /Users/nikiv/clones/wasm-git/test/common.js
- /Users/nikiv/clones/wasm-git/test/checkout.spec.js
      at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
      at Function.Module._load (node:internal/modules/cjs/loader:778:27)
      at Module.require (node:internal/modules/cjs/loader:999:19)
      at require (node:internal/modules/cjs/helpers:102:18)
      at module.exports.lgPromise (test/common.js:3:20)
      at new Promise (<anonymous>)
      at Object.<anonymous> (test/common.js:2:16)
      at Module._compile (node:internal/modules/cjs/loader:1099:14)
      at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
      at Module.load (node:internal/modules/cjs/loader:975:32)
      at Function.Module._load (node:internal/modules/cjs/loader:822:12)
      at Module.require (node:internal/modules/cjs/loader:999:19)
      at require (node:internal/modules/cjs/helpers:102:18)
      at Object.<anonymous> (test/checkout.spec.js:1:19)
      at Module._compile (node:internal/modules/cjs/loader:1099:14)
      at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
      at Module.load (node:internal/modules/cjs/loader:975:32)
      at Function.Module._load (node:internal/modules/cjs/loader:822:12)
      at ModuleWrap.<anonymous> (node:internal/modules/esm/translators:170:29)
      at ModuleJob.run (node:internal/modules/esm/module_job:198:25)
      at async Promise.all (index 0)
      at async ESMLoader.import (node:internal/modules/esm/loader:409:24)
      at async importModuleDynamicallyWrapper (node:internal/vm/module:437:15)

  4) nodefs
       should clone using nodefs:
     Error: Cannot find module './lg2.js'
Require stack:
- /Users/nikiv/clones/wasm-git/test/common.js
- /Users/nikiv/clones/wasm-git/test/checkout.spec.js
      at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
      at Function.Module._load (node:internal/modules/cjs/loader:778:27)
      at Module.require (node:internal/modules/cjs/loader:999:19)
      at require (node:internal/modules/cjs/helpers:102:18)
      at module.exports.lgPromise (test/common.js:3:20)
      at new Promise (<anonymous>)
      at Object.<anonymous> (test/common.js:2:16)
      at Module._compile (node:internal/modules/cjs/loader:1099:14)
      at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
      at Module.load (node:internal/modules/cjs/loader:975:32)
      at Function.Module._load (node:internal/modules/cjs/loader:822:12)
      at Module.require (node:internal/modules/cjs/loader:999:19)
      at require (node:internal/modules/cjs/helpers:102:18)
      at Object.<anonymous> (test/checkout.spec.js:1:19)
      at Module._compile (node:internal/modules/cjs/loader:1099:14)
      at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
      at Module.load (node:internal/modules/cjs/loader:975:32)
      at Function.Module._load (node:internal/modules/cjs/loader:822:12)
      at ModuleWrap.<anonymous> (node:internal/modules/esm/translators:170:29)
      at ModuleJob.run (node:internal/modules/esm/module_job:198:25)
      at async Promise.all (index 0)
      at async ESMLoader.import (node:internal/modules/esm/loader:409:24)
      at async importModuleDynamicallyWrapper (node:internal/vm/module:437:15)

  5) git revert
       "before each" hook for "should revert commit":
     Error: Cannot find module './lg2.js'
Require stack:
- /Users/nikiv/clones/wasm-git/test/common.js
- /Users/nikiv/clones/wasm-git/test/checkout.spec.js
      at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
      at Function.Module._load (node:internal/modules/cjs/loader:778:27)
      at Module.require (node:internal/modules/cjs/loader:999:19)
      at require (node:internal/modules/cjs/helpers:102:18)
      at module.exports.lgPromise (test/common.js:3:20)
      at new Promise (<anonymous>)
      at Object.<anonymous> (test/common.js:2:16)
      at Module._compile (node:internal/modules/cjs/loader:1099:14)
      at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
      at Module.load (node:internal/modules/cjs/loader:975:32)
      at Function.Module._load (node:internal/modules/cjs/loader:822:12)
      at Module.require (node:internal/modules/cjs/loader:999:19)
      at require (node:internal/modules/cjs/helpers:102:18)
      at Object.<anonymous> (test/checkout.spec.js:1:19)
      at Module._compile (node:internal/modules/cjs/loader:1099:14)
      at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
      at Module.load (node:internal/modules/cjs/loader:975:32)
      at Function.Module._load (node:internal/modules/cjs/loader:822:12)
      at ModuleWrap.<anonymous> (node:internal/modules/esm/translators:170:29)
      at ModuleJob.run (node:internal/modules/esm/module_job:198:25)
      at async Promise.all (index 0)
      at async ESMLoader.import (node:internal/modules/esm/loader:409:24)
      at async importModuleDynamicallyWrapper (node:internal/vm/module:437:15)

Not sure where the /lg2.js comes from.

TypeError: WebAssembly.instantiate(): Import #0 module="a" error: module is not an object or function

Hey Peter,

I am already successfully cloning my repository and committing files with [email protected].
Now, I want to try my luck in implementing git push functionality that can push to more branches than master and make that a PR to wasm-git.

I've run the setup.sh in the root folder and next build.sh in the emscripten build folder.
First, there was this error at one point during the compilation:

emcmake: error: '-cmake build ../libgit2 -DCMAKE_TOOLCHAIN_FILE=/usr/local/Cellar/emscripten/2.0.31/libexec/cmake/Modules/Platform/Emscripten.cmake -DCMAKE_CROSSCOMPILING_EMULATOR=/Users/ciesielskico/.nvm/versions/node/v14.17.0/bin/node' 
failed: [Errno 2] No such file or directory: '-cmake'

which I easily fixed by removing the hyphen on line 35 in build.sh:

emcmake cmake build ../libgit2

Running that gives me the following output

configure: cmake -DCMAKE_BUILD_TYPE=Debug "-DCMAKE_C_FLAGS=  --pre-js /Users/ciesielskico/Documents/wasm-git/emscriptenbuild/pre.js --post-js /Users/ciesielskico/Documents/wasm-git/emscriptenbuild/post.js -s \"EXTRA_EXPORTED_RUNTIME_METHODS=['FS','callMain']\" -lnodefs.js -lidbfs.js -s INVOKE_RUN=0 -s ALLOW_MEMORY_GROWTH=1" -DREGEX_BACKEND=regcomp -DSONAME=OFF -DUSE_HTTPS=OFF -DBUILD_SHARED_LIBS=OFF -DTHREADSAFE=OFF -DUSE_SSH=OFF -DBUILD_CLAR=OFF -DBUILD_EXAMPLES=ON ../libgit2 -DCMAKE_TOOLCHAIN_FILE=/usr/local/Cellar/emscripten/2.0.31/libexec/cmake/Modules/Platform/Emscripten.cmake -DCMAKE_CROSSCOMPILING_EMULATOR=/Users/ciesielskico/.nvm/versions/node/v14.17.0/bin/node
-- Checking prototype qsort_r for HAVE_QSORT_R_BSD - False
-- Checking prototype qsort_r for HAVE_QSORT_R_GNU - False
-- Could NOT find OpenSSL, try to set the path to OpenSSL root folder in the system variable OPENSSL_ROOT_DIR (missing: OPENSSL_CRYPTO_LIBRARY OPENSSL_INCLUDE_DIR)
-- Could NOT find PCRE (missing: PCRE_LIBRARY PCRE_POSIX_LIBRARY PCRE_INCLUDE_DIR)
-- http-parser version 2 was not found or disabled; using bundled 3rd-party sources.
-- Could NOT find ZLIB (missing: ZLIB_LIBRARY ZLIB_INCLUDE_DIR)
-- zlib was not found; using bundled 3rd-party sources.
-- LIBSSH2 not found. Set CMAKE_PREFIX_PATH if it is installed outside of the default search path.
-- Checking for module 'heimdal-gssapi'
--   No package 'heimdal-gssapi' found
-- Could NOT find GSSAPI (missing: GSSAPI_LIBRARIES GSSAPI_INCLUDE_DIR)
-- Enabled features:
 * nanoseconds, whether to use sub-second file mtimes and ctimes
 * tracing, tracing support
 * SHA, using CollisionDetection
 * regex, using system regcomp
 * http-parser, http-parser support (bundled)
 * zlib, using bundled zlib

-- Disabled features:
 * debugpool, debug pool allocator
 * threadsafe, threadsafe support
 * HTTPS
 * SSH, SSH transport support
 * ntlmclient, NTLM authentication support for Unix
 * SPNEGO, SPNEGO authentication support
 * iconv, iconv encoding conversion support

-- Configuring done
-- Generating done
-- Build files have been written to: /Users/ciesielskico/Documents/wasm-git/emscriptenbuild
configure: cmake build ../libgit2 -DCMAKE_TOOLCHAIN_FILE=/usr/local/Cellar/emscripten/2.0.31/libexec/cmake/Modules/Platform/Emscripten.cmake -DCMAKE_CROSSCOMPILING_EMULATOR=/Users/ciesielskico/.nvm/versions/node/v14.17.0/bin/node
-- Checking prototype qsort_r for HAVE_QSORT_R_BSD - False
-- Checking prototype qsort_r for HAVE_QSORT_R_GNU - False
-- Could NOT find OpenSSL, try to set the path to OpenSSL root folder in the system variable OPENSSL_ROOT_DIR (missing: OPENSSL_CRYPTO_LIBRARY OPENSSL_INCLUDE_DIR)
-- Could NOT find PCRE (missing: PCRE_LIBRARY PCRE_POSIX_LIBRARY PCRE_INCLUDE_DIR)
-- http-parser version 2 was not found or disabled; using bundled 3rd-party sources.
-- Could NOT find ZLIB (missing: ZLIB_LIBRARY ZLIB_INCLUDE_DIR)
-- zlib was not found; using bundled 3rd-party sources.
-- LIBSSH2 not found. Set CMAKE_PREFIX_PATH if it is installed outside of the default search path.
-- Checking for module 'heimdal-gssapi'
--   No package 'heimdal-gssapi' found
-- Could NOT find GSSAPI (missing: GSSAPI_LIBRARIES GSSAPI_INCLUDE_DIR)
-- Enabled features:
 * nanoseconds, whether to use sub-second file mtimes and ctimes
 * tracing, tracing support
 * SHA, using CollisionDetection
 * regex, using system regcomp
 * http-parser, http-parser support (bundled)
 * zlib, using bundled zlib

-- Disabled features:
 * debugpool, debug pool allocator
 * threadsafe, threadsafe support
 * HTTPS
 * SSH, SSH transport support
 * ntlmclient, NTLM authentication support for Unix
 * SPNEGO, SPNEGO authentication support
 * iconv, iconv encoding conversion support

-- Configuring done
-- Generating done
-- Build files have been written to: /Users/ciesielskico/Documents/wasm-git/emscriptenbuild
make: make
Consolidate compiler generated dependencies of target git2internal
[  1%] Building C object src/CMakeFiles/git2internal.dir/transports/emscriptenhttp.c.o
emcc: warning: linker setting ignored during compilation: 'EXTRA_EXPORTED_RUNTIME_METHODS' [-Wunused-command-line-argument]
emcc: warning: linker setting ignored during compilation: 'INVOKE_RUN' [-Wunused-command-line-argument]
emcc: warning: linker setting ignored during compilation: 'ALLOW_MEMORY_GROWTH' [-Wunused-command-line-argument]
/Users/ciesielskico/Documents/wasm-git/libgit2/src/transports/emscriptenhttp.c:112:13: warning: ISO C90 forbids mixing declarations and code [-Wdeclaration-after-statement]
    git_buf buf = GIT_BUF_INIT;
            ^
/Users/ciesielskico/Documents/wasm-git/libgit2/src/transports/emscriptenhttp.c:136:57: warning: unused parameter 'subtransport' [-Wunused-parameter]
static int emscriptenhttp_close(git_smart_subtransport *subtransport)
                                                        ^
2 warnings generated.
emcc: warning: argument unused during compilation: '-lnodefs.js' [-Wunused-command-line-argument]
emcc: warning: argument unused during compilation: '-lidbfs.js' [-Wunused-command-line-argument]
[ 79%] Built target git2internal
Consolidate compiler generated dependencies of target zlib
[ 84%] Built target zlib
Consolidate compiler generated dependencies of target http-parser
[ 85%] Built target http-parser
[ 85%] Linking C static library ../libgit2.a
[ 85%] Built target git2
Consolidate compiler generated dependencies of target lg2
[ 86%] Linking C executable lg2.js
emcc: warning: EXTRA_EXPORTED_RUNTIME_METHODS is deprecated, please use EXPORTED_RUNTIME_METHODS instead [-Wdeprecated]
[100%] Built target lg2

I see a couple of warnings and something about disabled features but it doesn't look critical to me.
I copy the generated lg2.js and lg2.wasm into my web app but now when importScripts is run I get the following error in the browser:

lg2.js:1550 Uncaught (in promise) RuntimeError: Aborted(TypeError: WebAssembly.instantiate(): Import #0 module="a" error: module is not an object or function)
    at abort (lg2.js:1550)
    at lg2.js:1715

Not quite sure how to continue after this. Google doesn't produce any good results that would help me solve this.
I'm running Mac OS with Node v14.17.0 if that helps.

Running libgit2 commands

Supercool! It actually works!

How can I run commands like:

opts.flags |= GIT_STATUS_OPT_INCLUDE_UNTRACKED |
		GIT_STATUS_OPT_RENAMES_HEAD_TO_INDEX |
		GIT_STATUS_OPT_RENAMES_INDEX_TO_WORKDIR;

git_status_list_new(&statuslist, g_repo, &opts);

(sorry for writing it C-style)?

P.S. This is the signature: https://libgit2.org/libgit2/#v1.5.1/group/status/git_status_list_new

P.P.S. Here's an example in this repo: https://github.com/petersalomonsen/wasm-git/blob/master/libgit2patchedfiles/examples/status.c

Also, is it possible to access repository tree, e.g. I want to test the repository structure, tree of commits, in my code.

Publish WASM files

I know you can make npm install wasm-git in a random directory and copy the wasm file, but I think it could be easier if you published them in /releases.

Support for Rust git2-rs compilation

Would it be possible to make the WASM version of libgit, work with the git2-rs bindings for Rust.

Rust is much easier to work with and has better support for WASM via wasm-bindgen. Having support for Rust, would make creating an in-browser git CLI using wasm-git for instance much easier, without being limited to what's in the libgit2 examples/ written in C

This was mentioned here rust-lang/git2-rs#871

wasm-git general question

Hi Peter,
I'm not sure how to contact you. I tried DMing you on Twitter, but you don't accept them (@learnwasm). I just have a few basic questions about wasm-git. I just started learning Wasm:

  1. I was under the impression that some libgit2 functionality (like SSH) is not really doable in the JS runtime. Is this different in Wasm and wasm-git? Specifically, can you do all Git commands (using GitHub as your repo) over HTTPS if you have a token (instead of a password)?
  2. Are there any limitations to wasm-git compared to libgit2 on a linux PC? I want to create both a client and a server in the same Webassembly runtime in a browser. In other words, I want to be able to push and pull and clone (etc...) from other browsers, and have them do the same.

Can't compile WASM-GIT

Hello,

first, thanks a lot for all you work on wasm-git it is an amazing piece of software. Unfortunately, I can't compile wasm-git:

configure: cmake -DCMAKE_BUILD_TYPE=Debug "-DCMAKE_C_FLAGS=  --pre-js /home/philipp/Schreibtisch/wasm-git/emscriptenbuild/pre.js --post-js /home/philipp/Schreibtisch/wasm-git/emscriptenbuild/post.js -s \"EXTRA_EXPORTED_RUNTIME_METHODS=['FS','callMain']\" -lnodefs.js -lidbfs.js -s INVOKE_RUN=0 -s ALLOW_MEMORY_GROWTH=1 -s STACK_SIZE=131072" -DREGEX_BACKEND=regcomp -DSONAME=OFF -DUSE_HTTPS=OFF -DBUILD_SHARED_LIBS=OFF -DTHREADSAFE=OFF -DUSE_SSH=OFF -DBUILD_CLAR=OFF -DBUILD_EXAMPLES=ON ../libgit2 -DCMAKE_TOOLCHAIN_FILE=/usr/share/emscripten/cmake/Modules/Platform/Emscripten.cmake -DCMAKE_CROSSCOMPILING_EMULATOR=/usr/bin/node;--experimental-wasm-threads
-- Could NOT find Threads (missing: Threads_FOUND) 
-- Checking for module 'heimdal-gssapi'
--   Package 'heimdal-gssapi', required by 'virtual:world', not found
-- Could NOT find GSSAPI (missing: GSSAPI_LIBRARIES GSSAPI_INCLUDE_DIR) 
-- Could NOT find OpenSSL, try to set the path to OpenSSL root folder in the system variable OPENSSL_ROOT_DIR (missing: OPENSSL_CRYPTO_LIBRARY OPENSSL_INCLUDE_DIR) 
-- http-parser version 2 was not found or disabled; using bundled 3rd-party sources.
-- Could NOT find PCRE (missing: PCRE_LIBRARY PCRE_INCLUDE_DIR) 
-- LIBSSH2 not found. Set CMAKE_PREFIX_PATH if it is installed outside of the default search path.
-- Could NOT find ZLIB (missing: ZLIB_LIBRARY ZLIB_INCLUDE_DIR) 
-- zlib was not found; using bundled 3rd-party sources.
CMake Error at /snap/cmake/1328/share/cmake-3.27/Modules/FindPackageHandleStandardArgs.cmake:230 (message):
  Could NOT find Threads (missing: Threads_FOUND)
Call Stack (most recent call first):
  /snap/cmake/1328/share/cmake-3.27/Modules/FindPackageHandleStandardArgs.cmake:600 (_FPHSA_FAILURE_MESSAGE)
  /snap/cmake/1328/share/cmake-3.27/Modules/FindThreads.cmake:226 (FIND_PACKAGE_HANDLE_STANDARD_ARGS)
  src/CMakeLists.txt:136 (find_package)


-- Configuring incomplete, errors occurred!
emcmake: error: 'cmake -DCMAKE_BUILD_TYPE=Debug "-DCMAKE_C_FLAGS=  --pre-js /home/philipp/Schreibtisch/wasm-git/emscriptenbuild/pre.js --post-js /home/philipp/Schreibtisch/wasm-git/emscriptenbuild/post.js -s \"EXTRA_EXPORTED_RUNTIME_METHODS=['FS','callMain']\" -lnodefs.js -lidbfs.js -s INVOKE_RUN=0 -s ALLOW_MEMORY_GROWTH=1 -s STACK_SIZE=131072" -DREGEX_BACKEND=regcomp -DSONAME=OFF -DUSE_HTTPS=OFF -DBUILD_SHARED_LIBS=OFF -DTHREADSAFE=OFF -DUSE_SSH=OFF -DBUILD_CLAR=OFF -DBUILD_EXAMPLES=ON ../libgit2 -DCMAKE_TOOLCHAIN_FILE=/usr/share/emscripten/cmake/Modules/Platform/Emscripten.cmake -DCMAKE_CROSSCOMPILING_EMULATOR=/usr/bin/node;--experimental-wasm-threads' failed (returned 1)
make: make lg2
make: *** Keine Regel, um „lg2“ zu erstellen.  Schluss.
emmake: error: 'make lg2' failed (returned 2)

I am on ubuntu 23.04 and have

cmake version 3.27.3
libpthread-stubs0-dev Version: 0.4-1build2

installed. Thanks a lot for your help!

Contribute an example with more libgit2 calls

I'd like to contribute an example with multiple libgit2 calls, rather than single lg2 point of entry.
As of now, I have "git init" + "git add" working.

It needs more exports in build.sh,
something like this:

emcmake cmake -DCMAKE_BUILD_TYPE=$BUILD_TYPE -DCMAKE_C_FLAGS="$EXTRA_CMAKE_C_FLAGS \
 -g -sINLINING_LIMIT -O0 --pre-js $(pwd)/pre.js $POST_JS -sEXPORTED_FUNCTIONS=['_main','_git_strarray_print','_git_index_add_bypath','_malloc','_git_repository_open_ext','_git_repository_init','_git_libgit2_init','_git_repository_index','_git_index_add_all'] -s \"EXTRA_EXPORTED_RUNTIME_METHODS=['FS','callMain','ccall','cwrap','lengthBytesUTF8','stringToUTF8','writeArrayToMemory','getValue','setValue']\" -lnodefs.js -lidbfs.js -s INVOKE_RUN=0 -s ALLOW_MEMORY_GROWTH=1 -s TOTAL_MEMORY=512MB -s STACK_SIZE=131072" -DREGEX_BACKEND=regcomp -DSONAME=OFF -DUSE_HTTPS=OFF -DBUILD_SHARED_LIBS=OFF -DTHREADSAFE=OFF -DUSE_SSH=OFF -DBUILD_CLAR=OFF -DBUILD_EXAMPLES=ON ../libgit2

Please note: more EXPORTED_FUNCTIONS and EXTRA_EXPORTED_RUNTIME_METHODS.
Should I leave it like this or put them in a kind of variable?

Most of these exports are only needed for my example.

Stops working because can't find user.name after a few commits and pushes

Here's something that seems to be a bug. I'm running the following webworker code on chrome. The index.html file is the same as in the examples directory, as is githttpserver.js. It all works, until the last push which fails.

var Module = {
  locateFile: function(s) {
    return 'https://unpkg.com/[email protected]/' + s;
  }
};

importScripts('https://unpkg.com/[email protected]/lg2.js');

Module.onRuntimeInitialized = () => {
  
  FS.mkdir('/working');
  FS.mount(MEMFS, { }, '/working');
  FS.chdir('/working');    
  
  FS.writeFile('/home/web_user/.gitconfig', '[user]\n' +
               'name = Test User\n' +
               'email = [email protected]');
  
  
  Module.callMain(['clone','http://localhost:5000/test.git', 'testrepo']);
  FS.chdir('/working/testrepo');    
  
  text = '';
  for (let i = 0; i < 6; i++) {
    console.log(i);
    text += 'x';
    FS.writeFile('./test.txt', text);
    Module.callMain(['add', '.']);
    Module.callMain(['commit','-m','commit ' + (i+1)]);
    Module.callMain(['push']);
  }
  
}

The error message is

Error creating signature [-3] - config value 'user.name' was not found

More specifically, here's what the console shows:

Screenshot from 2022-09-18 11-05-00

Clearly user.name is defined fine, since it works for the first 5 pushes.

Finally, note that this code uses unpkg.com/[email protected]. The same happens with unpkg.com/[email protected], but unpkg.com/[email protected] and below work fine.

Adding wasm-git inside a react app

I'm encountering an issue while integrating a project into my React app. Specifically, I'm referring to issue #16 for guidance. To troubleshoot, I attempted to utilize https://github.com/petersalomonsen/javascriptmusic However, I'm facing difficulty loading the lg2.js and lg2.wasm files from https://unpkg.com/[email protected]/

Upon inspection of the logs, it appears that the issue stems from the response header containing an incorrect MIME type. Instead of the expected application/wasm, the response is returning application/text.

I've also experimented with incorporating the npm module directly into my React app. However, this approach failed due to the absence of fs, path and similar dependecies which are found in node environment and are not in the app. Should I try polyfilling these dependencies?

Request for Suggestions:
I would greatly appreciate any suggestions or guidance on resolving this issue.

Some commands are not available

Some commands such as revparse, branch are not available. Will they get supported in the future? Thanks!

For example:

> lg.callMain(["branch"])
Command not found: branch
undefined

failed to create locked file when git clone

version:0.0.4

I'm trying to use wasm-git in a worker, which is spawned in electron renderer.I mouted file system with NODEFS, and call clone command . However, I got the following error:

图片

Here is the code in the worker script:

FS.mkdir('/working');
FS.mount(NODEFS, { root: '/User/xxxx/.config/my-app' }, '/working');
FS.chdir('/working');
lg.callMain([
    'clone',
    `https://github.com/petersalomonsen/wasm-git.git`,
    'workingTree',
]);

Did I miss something? In fact, .git is created in physical file system, but not the files in working tree.

图片

provide working example (with webpack too?)

Hi,
I'd be really interested in seeing a working example of your lib in a website, is the source of https://wasm-git.petersalomonsen.com/ available for example?

I couldn't make the example provided in the repo work in my browser, I tried multiple integrations with webpack without success so far, so I'm a bit frustrated. ^^

I have no experience with WASM and emscripten so that probably explains why too.

Any pointer would be welcome.

Thanks!

Recommend pratice for getting git message?

For instance, when I run git status, it would only display message in console.log(). I would like to receive the message and display it in the frontend website. For now, I have to do this trick: https://stackoverflow.com/a/52142526

However, if the website has more than 1 lib and they all spill everything to console.log than it will be very trouble to filter them.

Do we have better ways for this case?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.