Skip to content

Commit

Permalink
truncate status on small terminals
Browse files Browse the repository at this point in the history
When the TTY is too narrow to contain the output, the assumption
that a carriage return and whitespace while erase the line no
longer holds. Prior to printing, check the number of columns
available in the TTY.

See alire-project/alire#1329 for a demonstration of the issue.
  • Loading branch information
atalii committed Nov 17, 2023
1 parent 88dc863 commit 820a527
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 2 deletions.
2 changes: 2 additions & 0 deletions simple_logging.gpr
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ project Simple_Logging is
for Object_Dir use "obj";
for Library_Dir use "lib";

for Languages use ("C", "Ada");

package Builder is
for Switches ("ada") use ("-j0", "-g");
end Builder;
Expand Down
15 changes: 13 additions & 2 deletions src/simple_logging.adb
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,18 @@ with GNAT.IO;
with Simple_Logging.Decorators;
with Simple_Logging.Filtering;

with Interfaces.C;

pragma Warnings (Off);
-- This is compiler-internal unit. We only use the Clock, which is highly
-- unlikely to change its specification.
with System.OS_Primitives;
pragma Warnings (On);

package body Simple_Logging is
function Get_Term_Width return Interfaces.C.Int;
pragma Import
(Convention => C, Entity => Get_Term_Width, External_Name => "simple_logging_term_width");

---------
-- Log --
Expand Down Expand Up @@ -172,6 +177,8 @@ package body Simple_Logging is
Line : Unbounded_String;
Pred : Unbounded_String;
-- Status of the precedent scope, to eliminate duplicates

Effective_Length : Integer;
begin
for Status of Statuses loop
if Status.Level <= Simple_Logging.Level
Expand All @@ -187,7 +194,12 @@ package body Simple_Logging is
Line := Indicator & " " & Line;
end if;

return To_String (Line);
Effective_Length := Integer (Get_Term_Width);
if Effective_Length = -1 or else Effective_Length > Length (Line) then
Effective_Length := Length (Line);
end if;

return To_String (Head (Line, Effective_Length));
end Build_Status_Line;

-----------------------
Expand Down Expand Up @@ -255,5 +267,4 @@ package body Simple_Logging is
end if;
end;
end Step;

end Simple_Logging;
21 changes: 21 additions & 0 deletions src/term.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
#include <stdbool.h>
#include <sys/ioctl.h>
#include <termios.h>

bool ioctl_failure = false;

int simple_logging_term_width(void)
{
struct winsize x;
int r;

if (ioctl_failure) return -1;
r = ioctl(2, TIOCGWINSZ, &x);

if (r != 0) {
ioctl_failure = true;
return -1;
} else {
return x.ws_col;
}
}

0 comments on commit 820a527

Please sign in to comment.