Create a tree object from a temporary index using libgit2 - git2go - libgit2

On the command line I can do the following:
$ touch foo
$ GIT_INDEX_FILE=/tmp/tmp.d95ehfhUOffoo/index git add -A
$ GIT_INDEX_FILE=/tmp/tmp.d95ehfhUOffoo/index git status -s
A foo
$ git status -s
?? foo
$ GIT_INDEX_FILE=/tmp/tmp.d95ehfhUOffoo/index git write-tree
b8f7b1e052b441b53a969014803516bb7e681760
$ git cat-file -p b8f7b1e052b441b53a969014803516bb7e681760
100644 blob ae3fdc2989ae00d75ec106feadb78ed9f98ba41a .gitignore
100644 blob 4e1e0d2f722485c7d284fb5cd7da855826e39b5a .rspec
100644 blob 4bc0f1cdd31d348ddc0e91365c5be5a40104fa17 Dockerfile
100644 blob 7dc939ea79c2bd70d8d32416f9da8aa568029b05 Gemfile
100644 blob 145bb24613da12ffef73d5db34e89e2ea8e265ad LICENSE.txt
100644 blob b8a804e12699a964dbeb97b7a632250192421294 README.md
100644 blob 809eb5616adcc0ebb78862099794489bd5b5b1a0 Rakefile
100644 blob a18114c31713746a33a2e70d9914d1ef3e781425 foo
040000 tree 3c8a789fc07c8f35fb96a7e77896cbbf2384e3d7 lib
040000 tree a5e7e5d6a85504f30912a8f65a498d17fe989c01 spec
100755 blob 0dd422b073bc1123cdf4979432822db773463537 test
Note that when I run git status using the repository index it shows that foo has not been staged.
So, how can I do this with git2go? One attempt so far:
func Worktree() (string, error) {
› repo, err := git.OpenRepository(".")
› if err != nil {
› › return "", err
› }
› index, err := git.NewIndex()
› if err != nil {
› › return "", err
› }
› err = index.AddAll([]string{"."}, git.IndexAddDefault, nil)
› if err != nil {
› › return "", err
› }
› treeOid, err := index.WriteTreeTo(repo)
› if err != nil {
› › return "", err
› }
› return treeOid.String(), nil
}
Results in:
Error: Could not add paths to index. Index is not backed up by an existing repository.
How do I associate an in memory index with the repository?
There seem to be some libgit functions, such as git_index_open and git_index_read that have not been implemented in git2go. I've scanned a lot of code and read a lot of the libgit2 api.
Some pointers (no, not *pointers) would be great.

The purely in-memory index you have created doesn't know about any repository, which is why you have to use WriteIndexTo() and give it a Repository. For the same reason, any method which wants to use a relative path to a file won't work, because the index isn't associated with a repository and thus cannot know where the files are. You'd need to use IndexEntry instead and fill in the details.
If you need the relative path methods, you can grab the index from the repository and simply not write it back to disc, but create a tree from it, just like you do with your repository-less one. You can then just ignore the changes you've done in-memory.
If you need to re-use the Index from that repository, there's git_index_read() to re-read from the version on-disc, though I think it might not be wrapped in git2go at this time.

Related

serve html file from node_modules using react native static server and webview

Is it possible to serve an html file from within the node_modules folder? I know how to serve from the assets folder, something like:
<WebView
...
source={{uri:'file:///android_asset/project_a/index.html'}}/>
or the corresponding path for iOS, but how can I access the node_modules folder and serve a file from there? I've tried using require() and/or using the path to the module I want served but with no luck.
The idea is that, I want to avoid copy-pasting build files between projects (i.e., from the build folder of project A to the assets/www of project B), instead, I want publish project A as an npm package and npm install and serve it from project B. This also improves version management of the projects.
For Android, you can run a custom Gradle task that able to will handle copy your assets in build time.
Create a Gradle file in your module's root, like below:
(I presume your module name is react-native-my-awesome-module and your HTML files is under www folder in module's root.)
awesome.gradle:
/**
* Register HTML asset source folder
*/
android.sourceSets.main.assets.srcDirs += file("$buildDir/intermediates/ReactNativeMyAwesomeModule")
/**
* Task to copy HTML files
*/
afterEvaluate {
def targetDir = "../../node_modules/react-native-my-awesome-module/www";
def fileNames = [ "*.html" ];
def htmlCopyTask = tasks.create(
name: "copyReactNativeMyAwesomeModuleAssets",
type: Copy) {
description = "copy react native my awesome module assets."
into "$buildDir/intermediates/ReactNativeMyAwesomeModule/www"
fileNames.each { fileName ->
from(targetDir) {
include(fileName)
}
}
}
android.applicationVariants.all { def variant ->
def targetName = variant.name.capitalize()
def generateAssetsTask = tasks.findByName("generate${targetName}Assets")
generateAssetsTask.dependsOn(htmlCopyTask)
}
}
After installing the module, put the below line in your project's android/app/build.gradle file:
apply from: file("../../node_modules/react-native-my-awesome-module/awesome.gradle");
When you build your app, your assets under www folder will be copied from your module. You can access your resources in your app like below :
<WebView
source={{uri: 'file:///android_asset/www/index.html'}}
/>
I ended up adding a script to packages.json that copies the files of interest into the assets/www folder before starting the app. Something like:
"scripts": {
"copy:build": "node -e \"fs.copyFileSync('./node_modules/dir-of-module','./assets/www/build')\"",
"start-android": "npm run copyAssets && react-native run-android",
...
}
If there is a better alternative, please let me know!

Where NPM Install output goes? I cannot find it in stdout nor stderr

I am trying to get the output of the command npm install and show it in my cli module.
But I am getting only the result at the end, not the loading output with the progress bar.
Is maybe npm outputing in another place different from stdout and stderr?
This is my code in Typescript
import * as cp from 'child_process';
const child = cp.spawn('npm', ['install', 'some-module']);
child.stdout.setEncoding('utf8');
child.stdout.on('data', (chunk) => {
process.stdout.write(chunk);
});
child.stderr.setEncoding('utf8');
child.stderr.on('data', (chunk) => {
process.stdout.write(chunk);
});
This is the only output I get at the end of the process:
added 154 packages, and audited 505 packages in 52s
Where the loading bar and all the rest of the output go? Why it is not in stdout or stderr?

error building app with hermes: '..' is not recognized as an internal or external command

Building the react-native app on Windows 10.
The error is printed for line 165 of node_modules\react-native\react.gradle:
'..' is not recognized as an internal or external command, operable program or batch file
Line 165 is the 5th line in the following, starting with exec:
if (enableHermes) {
doLast {
def hermesFlags;
def hbcTempFile = file("${jsBundleFile}.hbc")
exec {
if (targetName.toLowerCase().contains("release")) {
// Can't use ?: since that will also substitute valid empty lists
hermesFlags = config.hermesFlagsRelease
if (hermesFlags == null) hermesFlags = ["-O", "-output-source-map"]
} else {
hermesFlags = config.hermesFlagsDebug
if (hermesFlags == null) hermesFlags = []
}
if (Os.isFamily(Os.FAMILY_WINDOWS)) {
commandLine("cmd", "/c", getHermesCommand(), "-emit-binary", "-out", hbcTempFile, jsBundleFile, *hermesFlags)
} else {
commandLine(getHermesCommand(), "-emit-binary", "-out", hbcTempFile, jsBundleFile, *hermesFlags)
}
}
ant.move(
file: hbcTempFile,
toFile: jsBundleFile
);
if (hermesFlags.contains("-output-source-map")) {
ant.move(
// Hermes will generate a source map with this exact name
file: "${jsBundleFile}.hbc.map",
tofile: jsCompilerSourceMapFile
);
exec {
// TODO: set task dependencies for caching
// Set up the call to the compose-source-maps script
workingDir(reactRoot)
if (Os.isFamily(Os.FAMILY_WINDOWS)) {
commandLine("cmd", "/c", *nodeExecutableAndArgs, composeSourceMapsPath, jsPackagerSourceMapFile, jsCompilerSourceMapFile, "-o", jsOutputSourceMapFile)
} else {
commandLine(*nodeExecutableAndArgs, composeSourceMapsPath, jsPackagerSourceMapFile, jsCompilerSourceMapFile, "-o", jsOutputSourceMapFile)
}
}
}
}
}
Here is the definition of hermescommand in android/app/build.gradle:
project.ext.react = [
enableHermes: true, // clean and rebuild if changing
// next added by Yossi
hermesCommand: "../../node_modules/hermesengine/win64-bin/hermes",
extraPackagerArgs: ["--sourcemap-output", "$buildDir/intermediates/assets/release/index.android.bundle.map"]
]
Which, as far as I understand, points to the following file:
node_modules\hermes-engine\win64-bin\hermes.exe
Any idea?
Updated definition in android/app/build.gradle (following the answer below):
project.ext.react = [
enableHermes: true, // clean and rebuild if changing
// -either- hermesCommand: "..\\..\\node_modules\\hermesengine\\win64-bin\\hermes",
// -or- hermesCommand: "../../node_modules/hermesengine/%OS-BIN%/hermes",
hermesCommand: "../../node_modules/hermesengine/%OS-BIN%/hermes",
extraPackagerArgs: ["--sourcemap-output", "$buildDir/intermediates/assets/release/index.android.bundle.map"]
]
The build output now, after the change, is the following:
> Task :app:bundleReleaseJsAndAssets
warning: the transform cache was reset.
Welcome to React Native!
Learn once, write anywhere
info Writing bundle output to:, C:\esites-grocery\test1\plumpclient\android\app\build\generated\assets\react\release\index.android.bundle
info Writing sourcemap output to:, C:\esites-grocery\test1\plumpclient\android\app\build/intermediates/assets/release/index.android.bundle.map
info Done writing bundle output
info Done writing sourcemap output
info Copying 141 asset files
info Done copying assets
The system cannot find the path specified.
> Task :app:bundleReleaseJsAndAssets FAILED
> Task :app:bundleReleaseJsAndAssets_SentryUpload_3001
Processing react-native sourcemaps for Sentry upload.
> Analyzing 2 sources
> Rewriting sources
> Adding source map references
Uploading sourcemaps for release com.plumpplum#RN62 Hermes+3001 distribution 3001
> Bundled 2 files for upload
> Uploaded release files to Sentry
> File upload complete
Source Map Upload Report
Minified Scripts
~/index.android.bundle (sourcemap at index.android.bundle.map)
Source Maps
~/index.android.bundle.map
> Task :app:bundleReleaseJsAndAssets_SentryUpload_1001
Processing react-native sourcemaps for Sentry upload.
> Analyzing 2 sources
> Rewriting sources
> Adding source map references
Uploading sourcemaps for release com.plumpplum#RN62 Hermes+1001 distribution 1001
> Bundled 2 files for upload
> Uploaded release files to Sentry
> File upload complete
Source Map Upload Report
Minified Scripts
~/index.android.bundle (sourcemap at index.android.bundle.map)
Source Maps
~/index.android.bundle.map
> Task :app:bundleReleaseJsAndAssets_SentryUpload_2001
Processing react-native sourcemaps for Sentry upload.
> Analyzing 2 sources
> Rewriting sources
> Adding source map references
Uploading sourcemaps for release com.plumpplum#RN62 Hermes+2001 distribution 2001
> Bundled 2 files for upload
> Uploaded release files to Sentry
> File upload complete
Source Map Upload Report
Minified Scripts
~/index.android.bundle (sourcemap at index.android.bundle.map)
Source Maps
~/index.android.bundle.map
> Task :app:bundleReleaseJsAndAssets_SentryUpload_4001
Processing react-native sourcemaps for Sentry upload.
> Analyzing 2 sources
> Rewriting sources
> Adding source map references
Uploading sourcemaps for release com.plumpplum#RN62 Hermes+4001 distribution 4001
> Bundled 2 files for upload
> Uploaded release files to Sentry
> File upload complete
Source Map Upload Report
Minified Scripts
~/index.android.bundle (sourcemap at index.android.bundle.map)
Source Maps
~/index.android.bundle.map
FAILURE: Build failed with an exception.
* Where:
Script 'C:\esites-grocery\test1\plumpclient\node_modules\react-native\react.gradle' line: 165
* What went wrong:
Execution failed for task ':app:bundleReleaseJsAndAssets'.
> Process 'command 'cmd'' finished with non-zero exit value 1
Here's more of react.gradle:
def getHermesCommand = {
// If the project specifies a Hermes command, don't second guess it.
if (!hermesCommand.contains("%OS-BIN%")) {
return hermesCommand
}
// Execution on Windows fails with / as separator
return hermesCommand
.replaceAll("%OS-BIN%", getHermesOSBin())
.replace('/' as char, File.separatorChar);
}
You are specifying ../../node_modules/hermesengine/win64-bin/hermes as the path, which is OS specific (as determined by not having an OS placeholder).
As per the comment, react.gradle therefore doesn't second guess your path and just passes it directly to the OS command interpreter.
This fails because your command interpreter does not allow / as directory separator.
Either specify a path that's valid for your system:
hermesCommand: "..\\..\\node_modules\\hermesengine\\win64-bin\\hermes",
Or specify an OS-independent path to let react.gradle transform it for each platform:
hermesCommand: "../../node_modules/hermesengine/%OS-BIN%/hermes",

how do I echo a message to the terminal at the end of npm install?

I've created a repo I want to be cloned
after cloning, you run npm install
How do I echo a log message to the terminal that will show up at the end of the installation?
In your case, you can add a post-install script, that outputs, for example, a string to the console if you mark a version as alpha.
package.json
{
"version": "1.2.3-alpha.2",
"scripts": {
"postinstall": "node postinstall.js"
}
}
postinstall.js
const package = require('./package.json')
console.log('End of installation');
//Example using properties from package.json
if (package.version.includes('alpha')) {
console.log('Warning: Alpha version!')
}
BONUS
Append this to the command --loglevel verbose and all logs will be saved to npm-debug.log in current working directory.
It will show the logs in realtime + saves the log to directory its running.
You can just edit npm config npm config edit and add loglevel=verbose

No mapping using babel and browserify in PlayFramework 2.5

I am writing a project that is based on the seed at git#github.com:maximebourreau/play-reactjs-es6-seed.git
It appears to work with the 2.3 play framework, but I am getting errors using the 2.5 framework.
When I try to load a page, it get the following error:
RuntimeException: No mapping for /path/to/root/target/web/browserify/main.js
The full stack trace is at the bottom of the message.
This is the file that browserify is writing, but it seems that play does not know how to map it to a URL. I was not able to find anything that says where the file should be written or how to add a new mapping. I am also happy to use a plugin to do the translation.
Where should I be writing the file, or how should I tell play how to map the file?
My build.sbt is
name := """myProject"""
version := "1.0-SNAPSHOT"
lazy val root = (project in file(".")).enablePlugins(PlayJava)
scalaVersion := "2.11.7"
libraryDependencies ++= Seq(
javaJdbc,
cache,
javaWs,
)
val browserifyTask = taskKey[Seq[File]]("Run browserify")
val browserifyOutputDir = settingKey[File]("Browserify output directory")
browserifyOutputDir := target.value / "web" / "browserify"
browserifyTask := {
println("Running browserify");
val outputFile = browserifyOutputDir.value / "main.js"
browserifyOutputDir.value.mkdirs
"./node_modules/.bin/browserify -t [ babelify --presets [ es2015 react ] ] app/assets/javascripts/main.jsx -o "+outputFile.getPath !;
List(outputFile)
}
sourceGenerators in Assets <+= browserifyTask
resourceDirectories in Assets += browserifyOutputDir.value
My routes file is
# Routes
# This file defines all application routes (Higher priority routes first)
# ~~~~
# An example controller showing a sample home page
GET / controllers.HomeController.index
# An example controller showing how to use dependency injection
GET /count controllers.CountController.count
# Map static resources from the /public folder to the /assets URL path
GET /assets/*file controllers.Assets.versioned(path="/public", file: Asset)
POST /assessment controllers.AsyncController.assessment
#
# Play can't find files in node_modules in 2.5+
#GET /node_modules/*file controllers.NodeModulesController.at(file)
#GET /node_modules/*file controllers.NodeModulesController.at(file: String)
GET /node_modules/*file controllers.NodeModulesController.versioned(file: String)
#GET /node_modules/*file controllers.Assets.versioned(path="/node_modules", file:Asset)
The stack trace is
scala.sys.package$.error(package.scala:27)
sbt.Mapper$$anonfun$fail$1.apply(PathMapper.scala:37)
sbt.Mapper$$anonfun$fail$1.apply(PathMapper.scala:37)
sbt.Alternatives$$anon$1$$anonfun$$bar$1$$anonfun$apply$3.apply(PathMapper.scala:117)
sbt.Alternatives$$anon$1$$anonfun$$bar$1$$anonfun$apply$3.apply(PathMapper.scala:117)
scala.Option.orElse(Option.scala:257)
sbt.Alternatives$$anon$1$$anonfun$$bar$1.apply(PathMapper.scala:117)
sbt.Alternatives$$anon$1$$anonfun$$bar$1.apply(PathMapper.scala:117)
sbt.PathFinder$$anonfun$pair$1.apply(Path.scala:135)
sbt.PathFinder$$anonfun$pair$1.apply(Path.scala:135)
scala.collection.TraversableLike$$anonfun$flatMap$1.apply(TraversableLike.scala:251)
scala.collection.TraversableLike$$anonfun$flatMap$1.apply(TraversableLike.scala:251)
scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59)
scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:47)
scala.collection.TraversableLike$class.flatMap(TraversableLike.scala:251)
scala.collection.AbstractTraversable.flatMap(Traversable.scala:105)
sbt.PathFinder.pair(Path.scala:135)
com.typesafe.sbt.jse.SbtJsTask$$anonfun$jsSourceFileTask$1$$anonfun$9$$anonfun$10$$anonfun$apply$4.apply(SbtJsTask.scala:292)
com.typesafe.sbt.jse.SbtJsTask$$anonfun$jsSourceFileTask$1$$anonfun$9$$anonfun$10$$anonfun$apply$4.apply(SbtJsTask.scala:286)
com.typesafe.sbt.web.SbtWeb$.withActorRefFactory(SbtWeb.scala:595)
com.typesafe.sbt.jse.SbtJsTask$$anonfun$jsSourceFileTask$1$$anonfun$9$$anonfun$10.apply(SbtJsTask.scala:285)
com.typesafe.sbt.jse.SbtJsTask$$anonfun$jsSourceFileTask$1$$anonfun$9$$anonfun$10.apply(SbtJsTask.scala:284)
scala.collection.immutable.Stream$$anonfun$map$1.apply(Stream.scala:376)
scala.collection.immutable.Stream$$anonfun$map$1.apply(Stream.scala:376)
scala.collection.immutable.Stream$Cons.tail(Stream.scala:1085)
scala.collection.immutable.Stream$Cons.tail(Stream.scala:1077)
scala.collection.immutable.Stream.foldLeft(Stream.scala:563)
scala.concurrent.Future$.sequence(Future.scala:491)
com.typesafe.sbt.jse.SbtJsTask$$anonfun$jsSourceFileTask$1$$anonfun$9.apply(SbtJsTask.scala:303)
com.typesafe.sbt.jse.SbtJsTask$$anonfun$jsSourceFileTask$1$$anonfun$9.apply(SbtJsTask.scala:272)
com.typesafe.sbt.web.incremental.package$.syncIncremental(package.scala:228)
com.typesafe.sbt.jse.SbtJsTask$$anonfun$jsSourceFileTask$1.apply(SbtJsTask.scala:271)
com.typesafe.sbt.jse.SbtJsTask$$anonfun$jsSourceFileTask$1.apply(SbtJsTask.scala:257)
scala.Function1$$anonfun$compose$1.apply(Function1.scala:47)
sbt.$tilde$greater$$anonfun$$u2219$1.apply(TypeFunctions.scala:40)
sbt.std.Transform$$anon$4.work(System.scala:63)
sbt.Execute$$anonfun$submit$1$$anonfun$apply$1.apply(Execute.scala:228)
sbt.Execute$$anonfun$submit$1$$anonfun$apply$1.apply(Execute.scala:228)
sbt.ErrorHandling$.wideConvert(ErrorHandling.scala:17)
sbt.Execute.work(Execute.scala:237)
sbt.Execute$$anonfun$submit$1.apply(Execute.scala:228)
sbt.Execute$$anonfun$submit$1.apply(Execute.scala:228)
sbt.ConcurrentRestrictions$$anon$4$$anonfun$1.apply(ConcurrentRestrictions.scala:159)
sbt.CompletionService$$anon$2.call(CompletionService.scala:28)
java.util.concurrent.FutureTask.run(FutureTask.java:266)
java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
java.util.concurrent.FutureTask.run(FutureTask.java:266)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
java.lang.Thread.run(Thread.java:745)
You must change two lines in build.sbt
List(outputFile) to Nil
and
resourceDirectories in Asset += browserifyOutputDir.value
to
unmanagedResources in Assets += baseDirectory.value / "target/web/browserify/main.js"
For example:
browserifyTask := {
println("Running browserify");
val outputFile = browserifyOutputDir.value / "main.js"
browserifyOutputDir.value.mkdirs
"./node_modules/.bin/browserify -t [ babelify --presets [ es2015 react ] ] app/assets/javascripts/main.jsx -o "+outputFile.getPath !;
Nil
}
sourceGenerators in Assets <+= browserifyTask
unmanagedResources in Assets += baseDirectory.value / "target/web/browserify/main.js"
I ran accross the same error message, and almost same stacktrace,
after starting a project from the same git repo: git#github.com:maximebourreau/play-reactjs-es6-seed.git
The latest version of the repo is using play 2.5 and works fine, so
I don't think play version is a problem.
I noticed that the error was mentioning [sbt-jshint] somewhere,
and removing this line from project/plugins.sbt fixed the problem for me:
addSbtPlugin("com.typesafe.sbt" % "sbt-jshint" % "1.0.3")