import test from 'ava';
import semver from 'semver';
import moment from 'moment';

import buildRevision from '../index';

test('build revision is semver compatible', async t => {
    const option = {
        cwd: 'test/fixture/package-valid/target'
    };

    const revision = await buildRevision(option);
    t.truthy(semver.valid(revision), 'semver could not parse a valid version');
});

test('throws error for package with missing version', async t => {
    const option = {
        cwd: 'test/fixture/package-invalid/target'
    };

    return buildRevision(option).then((res) => {
        t.fail('invalid package did not throw error');
    }, (err) => {
        t.truthy(err instanceof TypeError, err.message);
    });
});

test('buildinfo prefix is configurable', async t => {
    const PREFIX = 'REV'
    const option = {
        prefix: PREFIX,
        cwd: 'test/fixture/package-valid/target'
    };

    const revision = await buildRevision(option);
    t.truthy(semver.valid(revision) && revision.includes('+' + PREFIX), 'configured buildinfo prefix not set');
});

test('updates the existing buildinfo fragment of semver', async t => {
    const option = {
        cwd: 'test/fixture/package-with-buildinfo/target'
    };
    const fixtureVersion = require('./fixture/package-with-buildinfo/package.json').version;

    t.true((fixtureVersion.match(/\+/g) || []).length === 1, 'test fixture does not include buildinfo')
    const revision = await buildRevision(option);
    t.true(semver.valid(revision) && (revision.match(/\+/g) || []).length === 1, 'invalid version with multiple buildfragments generated');
});

test('generates ISO 8601 UTC timestamp for dirty builds', async t => {
    const option = {
        cwd: 'test/fixture/package-valid/target'
    };

    const revision = await buildRevision(option);
    const timestamp = revision.split('.').pop(); // get the last part
    t.true(moment(timestamp).isValid(), 'could not parse a valid timestamp');
});

test.todo('throws error when project is not a git clone');
test.todo('throws error when no SHA is found (e.g. localbuilds before initial git commit)');

@@ -1,12 +1,33 @@
+import fs from 'fs';%0A
 import test 
@@ -1784,32 +1784,198 @@
 target'%0A    %7D;%0A%0A
+    // Test Setup: Add a file to the fixtures direcory to make the repository it dirty%0A    fs.writeFileSync('test/fixture/package-valid/change.txt', 'dummychange');%0A%0A
     const revisi
@@ -2060,29 +2060,8 @@
 p();
- // get the last part
 %0A   
@@ -2134,16 +2134,262 @@
 stamp');
+%0A%0A    // Test Teardown: Reset repository%0A    fs.unlink('test/fixture/package-valid/change.txt', (err) =%3E %7B%0A        if (err) %7B%0A            t.fail('Could not reset test setup, other tests might be affected')%0A            throw err;%0A        %7D%0A    %7D);
 %0A%7D);%0A%0Ate

Fix failed build due to parsing error by momentjs