Source

buildcounter / buildcounter.c

/*

Copyright (c) 2012, <b.w (a) gmx (.) tm>

Permission to use, copy, modify, and/or distribute this software for any purpose
with or without fee is hereby granted, provided that the above copyright notice
and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
THIS SOFTWARE.

*/


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "buildno.h"

static const char *format = "#define BUILDNO %d\n";

static void print_usage(const char *argv0)
{
    fprintf(stderr, "Usage: %s <-s> [filename]\n", argv0);
    fprintf(stderr, "       -s: Silent mode\n\n");
    fprintf(stderr, "Build: %d (compiled on %s)\n", BUILDNO, __DATE__);
    fprintf(stderr, "Licensed under ISC license\n");
    fprintf(stderr, "https://bitbucket.org/Ragnara/buildcounter\n");
    exit(1);
}

////////////////////////////////////////////////////////////////////////////////

static char *parse_parameters(int argc, char **argv, _Bool *silent)
{
    if (argc < 2 || argc > 3)
    {
        fprintf(stderr, "Invalid number of parameters\n\n");
        print_usage(argv[0]);
    }

    if (!strcmp(argv[1], "--version") || !strcmp(argv[1], "-h") || !strcmp(argv[1], "--help"))
        print_usage(argv[0]);

    *silent = 0;
    int filename_index = 1;

    if(argc == 3)
    {
        if (!strcmp(argv[1], "-s"))
        {
            *silent = 1;
        }
        else if (strcmp(argv[1], "--"))
        {
            fprintf(stderr, "Invalid parameter '%s'\n\n", argv[1]);
            print_usage(argv[0]);
        }
        ++filename_index;
    }

    return argv[filename_index];
}

////////////////////////////////////////////////////////////////////////////////

int main(int argc, char **argv)
{
    _Bool silent = 0;
    char *filename = parse_parameters(argc, argv, &silent);

    FILE *file;
    int lastbuild = 0;

    if ((file = fopen(filename, "r")))
    {
        int res = fscanf(file, format, &lastbuild);
        fclose(file);

        if (res != 1)
        {
            fprintf(stderr, "File %s does not look like buildcounter output\n", filename);
            exit(1);
        }
    }

    if ((file = fopen(filename, "w")))
    {
        fprintf(file, format, ++lastbuild);
        fclose(file);

        if (!silent)
            printf(format, lastbuild);

    }
    else
    {
        perror("could not save last build to file");
    }


    return 0;
}