GithubHelp home page GithubHelp logo

node-git-describe's Introduction

git-describe

npm version npm license travis build vulnerabilities

This Node.js module runs git describe on the working directory or any other directory and parses the output to individual components. Additionally, if your tags follow semantic versioning the semver will be parsed and supplemented with the git-specific information as build metadata.

Installation

Available from npm: npm install git-describe

Tests are not included in the npm package โ€” clone the git repository to run tests (Node.js 4+ required).

As of version 4.0.0, semver is an optional dependency that does not have to be installed if you do not require semver functionality.

Note that the git executable must be in the system's executable path for this module to function.

Usage

The module exposes two functions:

  • gitDescribe(directory, options, cb) -> Promise
  • gitDescribeSync(directory, options) -> Object

The only difference is that gitDescribe has an asynchronous API (either the callback argument or the returned promise can be used), whilst gitDescribeSync is fully synchronous (blocks until the git executable returns and throws an Error on failure).

Both functions can take a directory string (defaults to working directory) and an options object. Either or both arguments can be omitted.

const {gitDescribe, gitDescribeSync} = require('git-describe');

// Target working directory
const gitInfo = gitDescribeSync();

// Target the directory of the calling script
// Recommended when you want to target the repo your app resides in
const gitInfo = gitDescribeSync(__dirname);

// With options (see below)
const gitInfo = gitDescribeSync(__dirname, {
    longSemver: true,
    dirtySemver: false
});

// Another example: working directory, use 16 character commit hash abbreviation
const gitInfo = gitDescribeSync({
    customArguments: ['--abbrev=16']
});

// Asynchronous with promise
gitDescribe(__dirname)
    .then((gitInfo) => console.dir(gitInfo))
    .catch((err) => console.error(err));

// Asynchronous with node-style callback
gitDescribe(__dirname, (err, gitInfo) => {
    if (err)
        return console.error(err);
    console.dir(gitInfo);
});

Example output

{ 
    dirty: false,
    hash: 'g3c9c15b',
    distance: 6,
    tag: 'v2.1.0-beta',
    semver: SemVer, // SemVer instance, see https://github.com/npm/node-semver
    suffix: '6-g3c9c15b',
    raw: 'v2.1.0-beta-6-g3c9c15b',
    semverString: '2.1.0-beta+6.g3c9c15b'
}

Options

Option Default Description
dirtyMark '-dirty' Dirty mark to use if repo state is dirty (see git describe's --dirty).
dirtySemver true Appends the dirty mark to semverString if repo state is dirty.
long true Always adds commit distance and hash to raw, suffix and .toString() (matches the behaviour of git describe's --long)
longSemver false Always adds commit distance and hash to semverString (similar to git describe's --long, but for semver).
requireAnnotated false Uses --tags if false, so that simple git tags are allowed.
match 'v[0-9]*' Uses --match to filter tag names. By default only tags resembling a version number are considered.
customArguments [] Array of additional arguments to pass to git describe. Not all arguments are useful and some may even break the library, but things like --abbrev and --candidates should be safe to add.

node-git-describe's People

Contributors

beruic avatar bobo96run avatar dependabot[bot] avatar saitho avatar timothyjones avatar tvdstaaij 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

Watchers

 avatar  avatar  avatar  avatar

node-git-describe's Issues

Type definition for match option should accept null/false value

Hi,

I noticed that node-git-describe recently got built-in (i.e. directly provided by the package) TypeScript definitions, that is such a nice added feature!! ๐Ÿ‘

While it helped me better use the library in several occasions, there is one specific situation at least where it seems to me that the types miss a use case: for the match option, I used to pass false boolean value to prevent any match from happening (no --match option used on git-describe command).

The current types accepts only a string value, which, in strict mode, does not even accept null.

match?: string;

Then if I pass any string value, it will replace the default value (which matches anything looking like a version)

match: 'v[0-9]*',

I can use the "*" wildcard, but this still tries to match a tag.

Whereas I used to pass it false to prevent any match attempt, which is correctly handled in that case in the JS code:

if (_.isString(options.match))
execArgs = execArgs.concat(['--match', options.match]);

Using match: undefined makes the TS error go away, but does not work with the JS code, because the default value is still used in that case (expected behavior of lodash.defaults)

At least when using match: null I can get the initial behavior, but this does not pass the current types.

Therefore it seems to me that it is an expected behavior to be able to specify null or false to the match option, when we want to disable the --match option of git-describe command, hence it should be added in the types?

TypeError: Cannot read property 'toString' of null

When on Node, trying to execute the main function it breaks without any error message.

$ node
> const { gitDescribe, gitDescribeSync } = require('git-describe');
> gitDescribe()
Promise {
  <pending>,
  domain: 
   Domain {
     domain: null,
     _events: { error: [Function: debugDomainError] },
     _eventsCount: 1,
     _maxListeners: undefined,
     members: [] } }
> (node:8132) UnhandledPromiseRejectionWarning: Error: Git returned with status ENOENT:
    at handleProcessResult (C:\Users\lucio\workspace\npl360-web-app\node_modules\git-describe\lib\git-describe.js:69:19)
    at wrapper (C:\Users\lucio\workspace\npl360-web-app\node_modules\lodash\lodash.js:5232:19)
    at exithandler (child_process.js:282:5)
    at ChildProcess.errorhandler (child_process.js:294:5)
    at emitOne (events.js:116:13)
    at ChildProcess.emit (events.js:211:7)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:196:12)
    at onErrorNT (internal/child_process.js:372:16)
    at _combinedTickCallback (internal/process/next_tick.js:138:11)
    at process._tickDomainCallback (internal/process/next_tick.js:218:9)
(node:8132) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:8132) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
> gitDescribeSync();
TypeError: Cannot read property 'toString' of null
    at handleProcessResult (C:\Users\lucio\workspace\npl360-web-app\node_modules\git-describe\lib\git-desc
ribe.js:70:20)
    at wrapper (C:\Users\lucio\workspace\npl360-web-app\node_modules\lodash\lodash.js:5232:19)
    at Object.gitDescribe (C:\Users\lucio\workspace\npl360-web-app\node_modules\git-describe\lib\git-descr
ibe.js:46:16)
    at Object.wrapper [as gitDescribeSync] (C:\Users\lucio\workspace\npl360-web-app\node_modules\lodash\lo
dash.js:5232:19)
TypeError: Cannot read property 'toString' of null
    at handleProcessResult (C:\Users\lucio\workspace\npl360-web-app\node_modules\git-describe\lib\git-desc
ribe.js:70:20)
    at wrapper (C:\Users\lucio\workspace\npl360-web-app\node_modules\lodash\lodash.js:5232:19)
    at Object.gitDescribe (C:\Users\lucio\workspace\npl360-web-app\node_modules\git-describe\lib\git-descr
ibe.js:46:16)
    at Object.wrapper [as gitDescribeSync] (C:\Users\lucio\workspace\npl360-web-app\node_modules\lodash\lo
dash.js:5232:19)

Running on Node v8.10.0 - let me know in case of more information required. Thanks!

distance must be included in the prerelease part of the semver string

From the spec item 3:

Once a versioned package has been released, the contents of that version MUST NOT be modified. Any modifications MUST be released as a new version.

So if we have commits on top of the tag, we must consider it as a different version.

From the spec item 9:

Pre-release versions have a lower precedence than the associated normal version. A pre-release version indicates that the version is unstable and might not satisfy the intended compatibility requirements as denoted by its associated normal version.

I think it's safe to assume that we can consider these commits as part of pre-release string.
Also, i think the distance should be added to the pre-release only if it is non-zero.

Make --long an optional arguement

It would be nice if a commit is a tag, that not the long format is used. For example our version is 0.3.2, with the --long format the following output is generated: 0.3.2-0-ge1c9efd. For backward compatibility the long option should be true by default.

tag attribute not returned

When executing the command "git describe" from the console from my node index.js directory, I get the answer => 0.0.1
When getting the result from the node app (index.js), the tag is not returned

const gitInfo = gitDescribeSync();

Result is as follow. And you ca see that tag is left to null

{
    "dirty": false,
    "raw": "828f514",
    "hash": "828f514",
    "distance": null,
    "tag": null,
    "semver": null,
    "suffix": "828f514",
    "semverString": null
}

Add option to generate dirty state hash of tracked files

This generates a unique id for for a given set of uncommitted changes in tracked files.

git diff | sha1sum | head -c 7

Here is an npm script that illustrates the idea behind dirty hash:

"git:version": "set -o pipefail && (set -o pipefail && git tag --points-at HEAD | grep -oP '^v\\d+\\.\\d+\\.\\d+$' | tr -d 'v' | xargs echo -n) || (set -o pipefail && git rev-parse --short HEAD | xargs echo -n) && (git diff-index --quiet HEAD || (set -o pipefail && echo -n '-dirty-' && git diff | sha1sum | head -c 7))",

Getting an error when using on Vue.js

I'm trying to run this in my Vue.js app to get the git info by running const gitInfo = gitDescribeSync() in a component and I'm getting the following error. I've imported it as import { gitDescribeSync } from "git-describe" as well. Do you know if it's possible to get this working with Vue.js or is it just a local problem on my end? Thanks!

TypeError: Expected a function
    at createWrap (lodash.js?f6f6:5553:1)
    at Function.eval (lodash.js?f6f6:10772:1)
    at apply (lodash.js?f6f6:489:1)
    at Function.eval [as partial] (lodash.js?f6f6:6627:1)
    at gitDescribe (git-describe.js?46cb:41:1)
    at wrapper (lodash.js?f6f6:5255:1)
    at VueComponent.intervalHandler (ManagementCluster.vue?4ecc:87:1)
    at VueComponent.mounted (ManagementCluster.vue?4ecc:63:1)
    at invokeWithErrorHandling (vue.runtime.esm.js?2b0e:1863:1)
    at callHook (vue.runtime.esm.js?2b0e:4235:1)

Would you like an additional maintainer?

Hi there! I've noticed that this repository hasn't had any changes in a few years - would you like a hand maintaining it?

Over the last few months, I've opened a couple of small issues (#16 and #17), which I would be happy to help fix. Additionally, it would be excellent to get #13 merged and released so that the vulnerability warning goes away. I'm depending on this package in a tool I'm using to generate human-friendly prerelease output (absolute-version, check it out here), so it feels appropriate to contribute back rather than fork it.

I know that maintaining open source is a lot of work (even for small changes), so I'd be happy to help out.

[usability issue] Doesn't return either `distance` or `semver`

I created a simple js file in the root of my project:

const { gitDescribeSync } = require('git-describe')
const gitInfo = gitDescribeSync()
console.log(gitInfo)

which returns:

{
  dirty: true,
  raw: 'd6d7fc7-dirty',
  hash: 'd6d7fc7',
  distance: null,
  tag: null,
  semver: null,
  suffix: 'd6d7fc7-dirty',
  semverString: null,
  toString: [Function (anonymous)]
}

like it couldn't acquire either of those. But git describe w/o params properly returns:

0.4.1-4-gd6d7fc7

The `hash` output property is prefixed with the VCS indicator

The commit hash part of the output for git-describe is always prefixed with a 'g', representing git as the VCS being used. It would make the output more useful in a copy/paste situation to strip that character off (or have an option to allow that as the output). I could see this also being more useful in machine parsing the output, although I'm sure most scripts already have a step to do this.

If you're open to this, I'll make a PR.

Make it possible to define dirty mark

Currently -dirty is appended to the version string when the repository is dirty. It would be cool with an option to define what should be appended (e.g. I want to append the current username).

Side note: Also. I don't understand why the dirty option is prepended with semver as it doesn't really have anything to do with semver that it is dirty.

Typescript types

First off, thank you for this excellent package!

Would you be interested in typescript types? I've just put some together so I can use it for a project I am working on - options include:

  1. Making a PR to convert the repo to typescript so that types are automatically generated
  2. Making a PR with manually created type definitions to https://github.com/DefinitelyTyped/DefinitelyTyped so that users can npm install --save-dev @types/git-describe
  3. Making a PR to include manually created type definitions here

I'm happy to do any of those options as you like, if you would be happy to see this happen.

Getting an 'empty' output with Vue.js as part of Jenkins build

I'm following the approach mentioned on https://stackoverflow.com/a/59951577/21503085

When I run my application locally, it works OK.
However, when the build is run with vue-cli-service build in our Jenkins CI/CD process then the commit hash is not picked up.

To help debug, I logged the output from gitDescribeSync() call:

{"dirty":false,"raw":"","hash":"","distance":null,"tag":null,"semver":null,"suffix":"","semverString":null}

I tried variations like gitDescribeSync(__dirname) and gitDescribeSync(__dirname, { match: '[0-9]*' }) without success.

I assume this is not a bug in this project, more something to do with how vue-cli-service works, but hoping someone can give some help/guidance how to make it work.

Unable to run

I get the following every time I try to run var gitInfo = gitDescribeSync(__dirname);.
I don't know if it has any significance, but I run it in my gulppfile.js.

The error is:

/home/jmk/Projekter/cordova/node_modules/git-describe/lib/git-describe.js:101
        output.semverString = output.semver.format();
                                           ^

TypeError: Cannot read property 'format' of null
  at self.parseDescription (/home/jmk/Projekter/cordova/node_modules/git-describe/lib/git-describe.js:101:44)
  at wrapper (/home/jmk/Projekter/cordova/node_modules/git-describe/node_modules/lodash/lodash.js:4710:19)
  at self.handleProcessResult (/home/jmk/Projekter/cordova/node_modules/git-describe/lib/git-describe.js:64:18)
  at wrapper (/home/jmk/Projekter/cordova/node_modules/git-describe/node_modules/lodash/lodash.js:4710:19)
  at self.gitDescribe (/home/jmk/Projekter/cordova/node_modules/git-describe/lib/git-describe.js:49:16)
  at wrapper (/home/jmk/Projekter/cordova/node_modules/git-describe/node_modules/lodash/lodash.js:4710:19)
  at Object.<anonymous> (/home/jmk/Projekter/cordova/gulpfile.js:7:15)
  at Module._compile (module.js:409:26)
  at Object.Module._extensions..js (module.js:416:10)
  at Module.load (module.js:343:32)
  at Function.Module._load (module.js:300:12)
  at Module.require (module.js:353:17)
  at require (internal/module.js:12:17)
  at Liftoff.handleArguments (/home/jmk/.node_modules/lib/node_modules/gulp/bin/gulp.js:116:3)
  at Liftoff.<anonymous> (/home/jmk/.node_modules/lib/node_modules/gulp/node_modules/liftoff/index.js:193:16)
  at module.exports (/home/jmk/.node_modules/lib/node_modules/gulp/node_modules/liftoff/node_modules/flagged-respawn/index.js:17:3)
  at Liftoff.<anonymous> (/home/jmk/.node_modules/lib/node_modules/gulp/node_modules/liftoff/index.js:185:9)
  at /home/jmk/.node_modules/lib/node_modules/gulp/node_modules/liftoff/index.js:159:9
  at /home/jmk/.node_modules/lib/node_modules/gulp/node_modules/v8flags/index.js:108:14
  at /home/jmk/.node_modules/lib/node_modules/gulp/node_modules/v8flags/index.js:36:12
  at /home/jmk/.node_modules/lib/node_modules/gulp/node_modules/v8flags/index.js:47:7
  at nextTickCallbackWith0Args (node.js:420:9)
  at process._tickCallback (node.js:349:13)
  at Function.Module.runMain (module.js:443:11)
  at startup (node.js:139:18)
  at node.js:968:3

Update:
Contextual information:

OS:     Ubuntu 16.04
NodeJS: 4.4.7 and 6.3.1

(Usability) Prefixed releases with release-please are not processed with semver

Hi,

I use a repository setup that involves releasing both a Helm chart and the app simultaneously. How release-please handles this is with a prefix. So I have tags of the style appname-v1.0.0-... and appname-helm-v1.0.0-.... I've changed the "match" to match appname-v[0-9]* but of course it does not filter the prefix before semver.parse(), which fails.

Could I have a way to either specify a group in the match to use (like appname-(v[0-9]*.*)) or some other method to match/filter a prefix?

A more general purpose solution could simply be an arbitrary format function that takes the tag and does something to it to make it semver compatible. I could do this on the other side, but I like the work you've put in to making the commit hash and number of commits to a semver-compatible format.

Cannot read property 'toString' of null when `git` is missing

When the git executable is missing, gitDescribeSync fails with the rather cryptic:

TypeError: Cannot read property 'toString' of null
    at handleProcessResult (...../node_modules/git-describe/lib/git-describe.js:70:20)

(you can reproduce this easily by changing the name of the executable on line 40)

It would be excellent if we could get a clearer error thrown in that case.

The hash is not prefixed with `g`

Contrary to what the documentation states the hash value is not (always?) prefixed with a g.

In #6 (comment) it was discussed that git describe (the command) prepends g to the hash, but this is actually not the case.

$ git log --oneline -1
d4ec867 (HEAD -> pact, origin/pact) ...

$ git describe --always
d4ec867

git describe (the command) will only prepend the g if a tag was found and HEAD does not point to the nearest tag.

I'm reporting here because of absolute-version/absolute-version-js#3

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.