Skip to content

Instantly share code, notes, and snippets.

@h4k1m0u
Last active April 3, 2024 18:25
Show Gist options
  • Save h4k1m0u/d54bb216332e6bc6f7e255936188f34b to your computer and use it in GitHub Desktop.
Save h4k1m0u/d54bb216332e6bc6f7e255936188f34b to your computer and use it in GitHub Desktop.
Script using Conan2 as a package manager for third-party libraries
cmake_minimum_required(VERSION 3.15)
project(Conan-Test)
# use C++20
set(CMAKE_CXX_STANDARD 20)
# autocomplete with YCM
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
set(CMAKE_BUILD_TYPE Release)
# dependencies installed with conan
find_package(fmt REQUIRED)
find_package(cpr REQUIRED)
find_package(nlohmann_json REQUIRED)
find_package(SQLiteCpp REQUIRED)
add_executable(${PROJECT_NAME} src/main.cpp)
target_link_libraries(${PROJECT_NAME} fmt::fmt cpr::cpr nlohmann_json::nlohmann_json SQLiteCpp)

Setup

  • Conan2 was installed on Archlinux by building its AUR package.
  • We follow Conan's official docs to setup CMake to use Conan:
$ conan install conanfile.txt --output-folder=build --build=missing
$ cd build
$ cmake -DCMAKE_TOOLCHAIN_FILE="conan_toolchain.cmake" ..
$ make -j
[requires]
fmt/10.2.1
cpr/1.10.5
nlohmann_json/3.11.3
sqlitecpp/3.3.1
[generators]
CMakeDeps
CMakeToolchain
// file: src/main.cpp
#include <iostream>
#include <SQLiteCpp/Database.h>
#include <SQLiteCpp/Statement.h>
#include <SQLiteCpp/SQLiteCpp.h>
#include <fmt/core.h>
#include <fmt/color.h>
#include <cpr/cpr.h>
#include <nlohmann/json.hpp>
using namespace nlohmann;
/* Fetch user details using a GET HTTP request & save them to a table in an sqlite database */
int main(int argc, char** argv) {
if (argc != 2) {
std::cout << "USAGE: " << argv[0] << " <GITHUB-USERNAME> " << '\n';
return 1;
}
// fetch user from github
std::string username = argv[1];
std::string url = "https://api.github.com/users/" + username;
cpr::Response r = cpr::Get(cpr::Url(url));
json res = json::parse(r.text);
std::string name = res["name"];
std::string login = res["login"];
fmt::print(fg(fmt::color::crimson) | fmt::emphasis::bold, "User '{}' fetched from Github!\n", name);
// insert fetched user into database (table users must exist beforehand)
SQLite::Database db("database.db", SQLite::OPEN_READWRITE);
SQLite::Transaction transaction(db);
SQLite::Statement query(db, "INSERT INTO users(name, login) VALUES (?, ?)");
query.bind(1, name);
query.bind(2, login);
query.exec();
transaction.commit();
fmt::print(fg(fmt::color::crimson) | fmt::emphasis::bold, "User inserted into databas\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment