Комментарии 20
А когда наконец можно будет посмотреть что-то слегка посложнее хелловорлда?
Я как раз дня 4 пердолюсь с chatgpt5 - на тему "как собрать lib7z.so 25.01 и накидать JNI wrapper с одним простейшим вызовом - распак файла". Иногда оно даже компилится, но нифига не пашет. Когда лимиты кончаются, то у chatgpt4 всё вообще тухло и делаю паузу. По кругу ещё не водит, но х.рню порет постоянно.
По сути задача для сишника джуна, от силы мидла (кодовая база у 7zip достаточно большая).
Где все эти аффтары прохладных историй где gpt влегкую рефакторит легаси. Ау?!
Попробуйте переформулировать вопрос на русском.
Кисть не виновата, что художник слепой. (С) я.
Задача для сишника Джуна, а вы 4 дня пердолитесь.
Вы умеете программировать? Или для вас это теоретическая задача по изучению возможностей нейросетей? Почему именно эта?
>Задача для сишника Джуна,
ну вот линус торвальдс за всю жизнь плюсовиком не стал, а вы от меня под одну второстепенную задачу требуете )))
я даже упростил уже задачу до "I've compiled 7z.so in linux with commands: cd CPP/7zip/Bundles/Format7zF make -j -f makefile.gcc please analyze project named bit7z on github and write me a simplest cpp console app that will use 7z.so directly and unpack supplied archive to directory"
и всё равно не вывозит. Я уже боюсь представлять сколько чайников можно было вскипятить вместо всего этого АИ-рукоблудия
По сути gpt не вывозит задачу, под которую заточен: проанализировать опенсорсный проект 7zip и четко выбрать нужные методы под нужную платформу. "программировать" от него вообще непонятно когда дождемся
// Simple extractor using bit7z library
// Compile: g++ -std=c++14 simple_extractor_bit7z.cpp -o extract -lbit7z -ldl
#include <iostream>
#include <bit7z/bitfileextractor.hpp>
using namespace bit7z;
int main(int argc, char* argv[])
{
if (argc != 3)
{
std::cout << "Usage: " << argv[0] << " <archive> <output_directory>" << std::endl;
std::cout << "Example: " << argv[0] << " test.7z /tmp/output" << std::endl;
return 1;
}
const std::string archivePath = argv[1];
const std::string outputDir = argv[2];
try
{
// Load 7z.so library
Bit7zLibrary lib{ "./7z.so" };
// Create extractor - BitFormat::Auto will auto-detect format
BitFileExtractor extractor{ lib, BitFormat::Auto };
// Extract archive
std::cout << "Extracting " << archivePath << " to " << outputDir << "..." << std::endl;
extractor.extract(archivePath, outputDir);
std::cout << "Extraction completed successfully!" << std::endl;
return 0;
}
catch (const BitException& ex)
{
std::cerr << "Error: " << ex.what() << std::endl;
return 1;
}
}Using bit7z (RECOMMENDED) - Just ~10 lines of code:
Bit7zLibrary lib{ "./7z.so" };
BitFileExtractor extractor{ lib, BitFormat::Auto };
extractor.extract(archivePath, outputDir);
Approach 1: Using bit7z (RECOMMENDED - Much Simpler)
### Installation
``bash
# Clone and build bit7z
git clone https://github.com/rikyoz/bit7z.git cd bit7z``
mkdir build && cd build
cmake .. -DCMAKE_BUILD_TYPE=Release
cmake --build . -j
sudo cmake --install .
### Compile and Run
```bash
# Compile
g++ -std=c++14 simple_extractor_bit7z.cpp -o extract -lbit7z -ldl
# Run
./extract archive.7z /tmp/output_dir
```
средний комментатор хабры тоже не вывозит задачу ))))
please analyze project named bit7z on github and write me a simplest cpp console app that will use 7z.so directly
Кстати, бесплатный GPT5 сфэйлил даже на "ЛАДНО, ДЕЛАЙ простейшую прогу через 7z.so + bit7z". Он упорно лепил пример под v3, хотя в readme для тупых всё расписано, про новый конструктор". Копипаста с гитхаба заработала. Правда насчёт автодетекта формата gpt опять обоср..сь, там надо компилять с флагом, который по умолчанию выкл.
Итого: gpt не переписывает легасятину. Переписывают по прежнему кожмешки.
// Simple 7z.so extractor - compile with: g++ -std=c++11 simple_7z_extractor.cpp -o extract7z -ldl
#include <iostream>
#include <string>
#include <dlfcn.h>
#include <sys/stat.h>
#include <sys/types.h>
// 7-Zip SDK header includes (you need these from p7zip or 7-Zip source)
#include "CPP/7zip/Archive/IArchive.h"
#include "CPP/7zip/IPassword.h"
#include "CPP/Common/MyCom.h"
#include "CPP/Windows/PropVariant.h"
#include "CPP/Common/MyString.h"
#include "CPP/7zip/Common/FileStreams.h"
using namespace NWindows;
// GUID for 7z format
#define CLSID_Format {0x23170F69, 0x40C1, 0x278A, {0x10, 0x00, 0x00, 0x01, 0x10, 0x07, 0x00, 0x00}}
// Extract callback class
class CArchiveExtractCallback :
public IArchiveExtractCallback,
public ICryptoGetTextPassword,
public CMyUnknownImp
{
public:
MY_UNKNOWN_IMP2(IArchiveExtractCallback, ICryptoGetTextPassword)
// IProgress
STDMETHOD(SetTotal)(UInt64 size);
STDMETHOD(SetCompleted)(const UInt64 *completeValue);
// IArchiveExtractCallback
STDMETHOD(GetStream)(UInt32 index, ISequentialOutStream **outStream, Int32 askExtractMode);
STDMETHOD(PrepareOperation)(Int32 askExtractMode);
STDMETHOD(SetOperationResult)(Int32 resultEOperationResult);
// ICryptoGetTextPassword
STDMETHOD(CryptoGetTextPassword)(BSTR *password);
private:
CMyComPtr<IInArchive> _archiveHandler;
UString _directoryPath;
UString _filePath;
COutFileStream *_outFileStreamSpec;
CMyComPtr<ISequentialOutStream> _outFileStream;
public:
void Init(IInArchive *archiveHandler, const UString &directoryPath);
UInt64 NumErrors;
CArchiveExtractCallback() : NumErrors(0) {}
};
void CArchiveExtractCallback::Init(IInArchive *archiveHandler, const UString &directoryPath)
{
NumErrors = 0;
_archiveHandler = archiveHandler;
_directoryPath = directoryPath;
}
STDMETHODIMP CArchiveExtractCallback::SetTotal(UInt64 /* size */)
{
return S_OK;
}
STDMETHODIMP CArchiveExtractCallback::SetCompleted(const UInt64 * /* completeValue */)
{
return S_OK;
}
STDMETHODIMP CArchiveExtractCallback::GetStream(UInt32 index, ISequentialOutStream **outStream, Int32 askExtractMode)
{
*outStream = nullptr;
_outFileStream.Release();
// Get archived file name
NCOM::CPropVariant prop;
RINOK(_archiveHandler->GetProperty(index, kpidPath, &prop));
UString fullPath;
if (prop.vt == VT_EMPTY)
fullPath = L"[Content]";
else
{
if (prop.vt != VT_BSTR)
return E_FAIL;
fullPath = prop.bstrVal;
}
_filePath = _directoryPath + fullPath;
if (askExtractMode != NArchive::NExtract::NAskMode::kExtract)
return S_OK;
// Check if it's a directory
NCOM::CPropVariant prop2;
RINOK(_archiveHandler->GetProperty(index, kpidIsDir, &prop2));
if (prop2.vt == VT_BOOL && prop2.boolVal != VARIANT_FALSE)
{
// Create directory
mkdir(GetAnsiString(_filePath).c_str(), 0755);
return S_OK;
}
// Create parent directories if needed
int slashPos = _filePath.ReverseFind(WCHAR_PATH_SEPARATOR);
if (slashPos >= 0)
{
UString dirPath = _filePath.Left(slashPos);
mkdir(GetAnsiString(dirPath).c_str(), 0755);
}
// Create file stream
_outFileStreamSpec = new COutFileStream;
CMyComPtr<ISequentialOutStream> outStreamLoc(_outFileStreamSpec);
if (!_outFileStreamSpec->Open(GetSystemString(_filePath), false))
{
std::cout << "Cannot open output file: " << GetAnsiString(_filePath) << std::endl;
NumErrors++;
return S_OK;
}
_outFileStream = outStreamLoc;
*outStream = outStreamLoc.Detach();
return S_OK;
}
STDMETHODIMP CArchiveExtractCallback::PrepareOperation(Int32 /* askExtractMode */)
{
return S_OK;
}
STDMETHODIMP CArchiveExtractCallback::SetOperationResult(Int32 operationResult)
{
if (operationResult != NArchive::NExtract::NOperationResult::kOK)
{
NumErrors++;
switch(operationResult)
{
case NArchive::NExtract::NOperationResult::kUnsupportedMethod:
std::cout << "Unsupported Method" << std::endl;
break;
case NArchive::NExtract::NOperationResult::kCRCError:
std::cout << "CRC Failed" << std::endl;
break;
case NArchive::NExtract::NOperationResult::kDataError:
std::cout << "Data Error" << std::endl;
break;
default:
std::cout << "Unknown Error" << std::endl;
}
}
return S_OK;
}
STDMETHODIMP CArchiveExtractCallback::CryptoGetTextPassword(BSTR *password)
{
// Password not supported in this simple example
return E_ABORT;
}
// Open callback class
class CArchiveOpenCallback :
public IArchiveOpenCallback,
public ICryptoGetTextPassword,
public CMyUnknownImp
{
public:
MY_UNKNOWN_IMP2(IArchiveOpenCallback, ICryptoGetTextPassword)
STDMETHOD(SetTotal)(const UInt64 *files, const UInt64 *bytes);
STDMETHOD(SetCompleted)(const UInt64 *files, const UInt64 *bytes);
STDMETHOD(CryptoGetTextPassword)(BSTR *password);
};
STDMETHODIMP CArchiveOpenCallback::SetTotal(const UInt64 * /* files */, const UInt64 * /* bytes */)
{
return S_OK;
}
STDMETHODIMP CArchiveOpenCallback::SetCompleted(const UInt64 * /* files */, const UInt64 * /* bytes */)
{
return S_OK;
}
STDMETHODIMP CArchiveOpenCallback::CryptoGetTextPassword(BSTR * /* password */)
{
return E_ABORT;
}
// Function type for CreateObject
typedef UINT32 (WINAPI *CreateObjectFunc)(const GUID *clsID, const GUID *iid, void **outObject);
int main(int argc, char* argv[])
{
if (argc != 3)
{
std::cout << "Usage: " << argv[0] << " <archive.7z> <output_directory>" << std::endl;
return 1;
}
const char* archivePath = argv[1];
const char* outputDir = argv[2];
// Load 7z.so
void* lib = dlopen("./7z.so", RTLD_LAZY);
if (!lib)
{
std::cerr << "Cannot load 7z.so: " << dlerror() << std::endl;
return 1;
}
// Get CreateObject function
CreateObjectFunc createObjectFunc = (CreateObjectFunc)dlsym(lib, "CreateObject");
if (!createObjectFunc)
{
std::cerr << "Cannot find CreateObject function" << std::endl;
dlclose(lib);
return 1;
}
// Create archive handler
GUID clsid = CLSID_Format;
CMyComPtr<IInArchive> archive;
if (createObjectFunc(&clsid, &IID_IInArchive, (void **)&archive) != S_OK)
{
std::cerr << "Cannot create IInArchive object" << std::endl;
dlclose(lib);
return 1;
}
// Open archive file
CInFileStream *fileSpec = new CInFileStream;
CMyComPtr<IInStream> file = fileSpec;
if (!fileSpec->Open(GetSystemString(GetUnicodeString(archivePath))))
{
std::cerr << "Cannot open archive file: " << archivePath << std::endl;
dlclose(lib);
return 1;
}
// Open archive
CArchiveOpenCallback *openCallbackSpec = new CArchiveOpenCallback;
CMyComPtr<IArchiveOpenCallback> openCallback(openCallbackSpec);
const UInt64 scanSize = 1 << 23;
if (archive->Open(file, &scanSize, openCallback) != S_OK)
{
std::cerr << "Cannot open archive: " << archivePath << std::endl;
dlclose(lib);
return 1;
}
// Create output directory
mkdir(outputDir, 0755);
// Extract
CArchiveExtractCallback *extractCallbackSpec = new CArchiveExtractCallback;
CMyComPtr<IArchiveExtractCallback> extractCallback(extractCallbackSpec);
extractCallbackSpec->Init(archive, GetUnicodeString(outputDir) + L"/");
std::cout << "Extracting archive..." << std::endl;
HRESULT result = archive->Extract(nullptr, (UInt32)(Int32)(-1), false, extractCallback);
if (result != S_OK)
{
std::cerr << "Extract error!" << std::endl;
dlclose(lib);
return 1;
}
if (extractCallbackSpec->NumErrors > 0)
{
std::cerr << "Extraction completed with " << extractCallbackSpec->NumErrors << " errors" << std::endl;
dlclose(lib);
return 1;
}
std::cout << "Extraction completed successfully!" << std::endl;
archive->Close();
dlclose(lib);
return 0;
}Using 7z.so directly - Requires ~300+ lines with:
Dynamic loading of 7z.so via dlopen()
Implementing COM-like interfaces (IInArchive, IArchiveExtractCallback)
Manual callback handling for file extraction
Complex error handling
Approach 2: Using 7z.so Directly (More Complex)
This requires understanding the 7-Zip COM-like interface and implementing callbacks.
### Requirements
You need header files from the 7-Zip SDK. Download from: https://www.7-zip.org/sdk.html
Required headers:
````
CPP/7zip/Archive/IArchive.h
CPP/7zip/IPassword.h
CPP/Common/MyCom.h
CPP/Windows/PropVariant.h
CPP/Common/MyString.h
CPP/7zip/Common/FileStreams.h
### Compile
```bash
# Assuming 7-Zip SDK is in ./p7zip
g++ -std=c++11 -I./p7zip simple_7z_extractor.cpp -o extract_direct -ldl
# Run
./extract_direct archive.7z /tmp/output_dir
```
скопипастил, запустил
g++ -std=c++11 simple_7z_extractor.cpp -o extract7z -ldl
вываливает несколько ЭКРАНОВ ошибок.
Причём не про пути, а всякое типа
ISO C++ forbids declaration of ‘MY_UNKNOWN_IMP2’ with no type [-fpermissive]
получется что либо gpt сгенерило какой-то голимый мусор, либо ключи правильные "забыло". Хотя ошибок столько, что явно допиливать напильником надо 90% этого опуса
а судя по
#define CLSID_Format {0x23170F69, 0x40C1, 0x278A, {0x10, 0x00, 0x00, 0x01, 0x10, 0x07, 0x00, 0x00}}
про остальные форматы тоже можно забыть (даже если бы оно закомпилялось).
Спасибо за пруф моей позиции - gpt мусор ) это платное такое выдало?
Да, один ваш промт на английском. Платный да. Не gpt, а Claude. Возможно с одной итерации не сделать, нужно несколько подходов.
просто ЛОЛушки.... поставил курсор, чтобы приобщиться к прекрасному ужасному модному-молодёжному.
Первая мысль: вау, программы сами пишуццо, ну всё.
По факту, простейшая вещь (уже java)
in ElasticService class write method to use scroll api to on index mails, sort by field tsIndex and make depth configurable to get all entities with field "path" NOT ending with "7z"
return as Map<String,String> key = entity "_id" , value is path
claude 4.5 навысирало нагенерило 2 экрана
Now I need to update the query to include the date range filter:
+6
Let me check for any linter errors:
Found 1 errorin ElasticService.java
I need to fix the range query syntax. Let me correct it:
Invalid: old_string and new_string are exactly the same.
Let me check the correct syntax for range queries in the Elasticsearch client:
Invalid: old_string and new_string are exactly the same.
Let me read the current state of the file to see the exact syntax:
ReadElasticService.java L440-454
I need to check what the correct method name is for range queries. Let me look at other examples in the codebase:
Greppedrange.*field in src
Let me check the Elasticsearch client documentation approach. I'll try a different syntax:
Invalid: old_string and new_string are exactly the same.
Let me try a different approach. I'll use the correct range query syntax:
Invalid: old_string and new_string are exactly the same.
Let me check the imports to see what range query classes are available:
ReadElasticService.java L1-20
I need to add the proper import for range queries. Let me add it:
+1
Now let me fix the range query syntax using the proper RangeQuery type:
+2-2
Now let me check for any remaining linter errors:
Found 2 errorsin ElasticService.java
The RangeQuery import is incorrect. Let me check what the correct import should be by looking at the existing code patterns:
я уж хотел пристрелить бедолагу и тут, просто шедевр:
I'll fix the errors in the getMailPathsNotEndingWith7z method. Let me use the correct script syntax that's already used elsewhere in the file:
вау, удалось списать у меня же. Определенно это стоит и 20 и 200 баксов )))))))))
# Makefile for 7z extractors
CXX = g++
CXXFLAGS = -std=c++14 -O2 -Wall
# Path to 7-Zip SDK (adjust this to your SDK location)
SEVENZ_SDK = ./p7zip
# For bit7z approach (simpler)
bit7z: simple_extractor_bit7z.cpp
$(CXX) $(CXXFLAGS) simple_extractor_bit7z.cpp -o extract_bit7z -lbit7z -ldl
@echo "Built extract_bit7z - Usage: ./extract_bit7z <archive> <output_dir>"
# For direct 7z.so approach (more complex, requires 7-Zip SDK headers)
direct: simple_7z_extractor.cpp
$(CXX) $(CXXFLAGS) -I$(SEVENZ_SDK) simple_7z_extractor.cpp -o extract_direct -ldl
@echo "Built extract_direct - Usage: ./extract_direct <archive> <output_dir>"
clean:
rm -f extract_bit7z extract_direct
.PHONY: bit7z direct cleanКоманды
Открою вам тайну - мгновенно отвечающий ChatGPT ни черта не может. Только ChatGPT 5 Thinking умеет более-менее нормально в кодинг, но судя по вашей оговорке про лимиты - это значит, что вы бесплатный юзер и вам доступен лишь один запрос к Thinking версии и всего десять к ChatGPT 5 Instant (Я не понимаю, как при обычном использовании вообще можно потратить лимит в 3000 запросов в неделю для Thinking версии у пользователей Plus, поэтому вы можете быть только бесплатным юзеров)
Если тратить на задачу $200, то открывается куча других возможностей - задонатить автору 7zip, или автору sevenzipjbindings, просто нанять фрилансера или пердолить бесплатный аккаунт chatgpt ещё неделю, а 200 баксов оставить себе )
Опустим размышления про то что ЗП за неделю пердолинга намного больше $200, но к сожалению много где ещё не дадут денег на "быстро зааутсорсить задачу", даже если это в разы выгоднее чем решать самому.
использование специфичной терминологии, слишком жёсткие ограничения, противоречивые команды - и вуаля, даже самая продвинутая сетка порет вам вам чушь.
почему-то при это у других людей таких проблем нет, странно, да? или что, все вокруг врут, и это всё заговор?))
Зарегистрируйтесь на Хабре, чтобы оставить комментарий
Чат-бот для сайта всего за 8 минут. OpenAI представила конструктор ИИ-агентов AgentKit