summaryrefslogtreecommitdiff
path: root/cli-hive.pl
blob: a3694be88244dd97f1581b78c0f96ba3e9f3d924 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#!/usr/bin/perl

use strict;
use warnings;

use Data::Dumper;
use File::Tail;
use JSON;
use Digest::SHA qw(sha256_hex);
use Net::Domain qw(hostfqdn);
use Storable;

our %DEFAULT_DATA = (
    user => $ENV{'USER'},
    hostname => hostfqdn(),
    shell => 'zsh',
);

our %PROCESSED;

sub read_processed {
    return unless -f "$ENV{'HOME'}/.cli-hive.processed";
    %PROCESSED = %{retrieve "$ENV{'HOME'}/.cli-hive.processed"};
}

sub store_processed {
    store \%PROCESSED, "$ENV{'HOME'}/.cli-hive.processed",
}

sub record_to_json {
    my $timestamp = shift;
    my $lines = shift;
    my %json = (
        timestamp => $timestamp,
        command => join '\\n', @$lines,
    );
    @json{keys %DEFAULT_DATA} = values %DEFAULT_DATA;

    #print encode_json \%json;
    print Dumper \%json;
    print "\n";
}

sub zsh_extract_timestamp {
    my $line = shift;
    my ($timestamp, $command) = $line =~ /^: (\d+).*?;(.*)/;

    return ($timestamp, $command) if defined $command;
    return (undef, $line);
}

sub checksum {
    my $timestamp = shift;
    my @fields = @_;

    push @fields, $timestamp if defined $timestamp;
    sha256_hex(join '', @fields);
}

sub record_reader {
    my ($timestamp, @lines);

    return sub {
        my $line = shift;

        my ($timestamp_, $command) =  zsh_extract_timestamp $line;
        $timestamp = $timestamp_ if defined $timestamp_;

        if ($command =~ /\\$/) {
            chomp $command;
            push @lines, $command;
            return;
        }

        if (defined $timestamp) {
            chomp $command;
            push @lines, $command;

            my $checksum = checksum $timestamp, @lines;
            unless (exists $PROCESSED{$checksum}) {
                record_to_json $timestamp, \@lines;
                $PROCESSED{$checksum} = {
                    timestamp => time,
                };
                store_processed;
            } 
        }

        @lines = ();
        $timestamp = undef;
    };
}

sub follow_history {
    my $file = File::Tail->new(
        name => "$ENV{'HOME'}/.zsh_history",
        interval => 0.1,
        maxinterval => 1,
    );

    my $reader = record_reader;
    while (defined(my $line = $file->read)) {
        $reader->($line);
    }
}

read_processed;
follow_history;