Skip to content

Commit ceaace5

Browse files
committed
Refactor download command
- Fixes #312 (downloads tax regime files) - Fixes #313 (creates `updated_at.txt` without using dados.gov.br) - Deprecate `--mirror` (costs of maintaining the mirror is too high) - Deprecate `has-update` and `updated-at` because fetching the updated at date is always changing and these commands do not seem to be heavily used (in other words, reduce complexity by removing features to facilitate maintainability)
1 parent beb396f commit ceaace5

11 files changed

+126
-359
lines changed

cmd/cmd.go

-2
Original file line numberDiff line numberDiff line change
@@ -87,8 +87,6 @@ func CLI() *cobra.Command {
8787
apiCLI(),
8888
downloadCLI(),
8989
urlsCLI(),
90-
updatedAtCLI(),
91-
hasUpdateCLI(),
9290
checkCLI(),
9391
createCmd,
9492
dropCmd,

cmd/download.go

+4-41
Original file line numberDiff line numberDiff line change
@@ -12,21 +12,15 @@ const (
1212
Downloads the required ZIP and Excel files.
1313
1414
The main files are downloaded from the official website of the Brazilian
15-
Federal Revenue. An extra Excel file is downloaded from IBGE. Since the server
16-
is extremely slow, all files are downloaded using multiple HTTP requests with
15+
Federal Revenue. An extra CSV file is downloaded from IBGE. Since the server
16+
might be slow, all files are downloaded using multiple HTTP requests with
1717
small content ranges.`
1818

1919
urlsHelper = `
20-
Shows the URLs of the required ZIP and Excel files.
20+
Shows the URLs of the required ZIP and CSV files.
2121
2222
The main files are downloaded from the official website of the Brazilian
23-
Federal Revenue. An extra Excel file is downloaded from IBGE.`
24-
25-
hasUpdateHelper = `
26-
Checks if there is an update available when it comes to the required ZIP from
27-
the Federal Revenue.
28-
29-
Exists with exit code 0 if there is an update available and 1 otherwise.`
23+
Federal Revenue. An extra CSV file is downloaded from the National Treasure.`
3024
)
3125

3226
var (
@@ -36,7 +30,6 @@ var (
3630
chunkSize int64
3731
skipExistingFiles bool
3832
restart bool
39-
useMirror string
4033
)
4134

4235
var downloadCmd = &cobra.Command{
@@ -51,9 +44,6 @@ var downloadCmd = &cobra.Command{
5144
if err != nil {
5245
return err
5346
}
54-
if useMirror != "" {
55-
return download.DownloadFromMirror(useMirror, dir, dur, skipExistingFiles, restart, parallelDownloads, downloadRetries, chunkSize)
56-
}
5747
return download.Download(dir, dur, skipExistingFiles, restart, parallelDownloads, downloadRetries, chunkSize)
5848
},
5949
}
@@ -72,23 +62,6 @@ var urlsCmd = &cobra.Command{
7262
},
7363
}
7464

75-
var updatedAtCmd = &cobra.Command{
76-
Use: "updated-at",
77-
Short: "Shows the latest updated at date of the required ZIP from the Federal Revenue.",
78-
RunE: func(_ *cobra.Command, _ []string) error {
79-
return download.UpdatedAt()
80-
},
81-
}
82-
83-
var hasUpdateCmd = &cobra.Command{
84-
Use: "has-update",
85-
Short: "Checks if there is an update available when it comes to the required ZIP from the Federal Revenue.",
86-
Long: hasUpdateHelper,
87-
RunE: func(_ *cobra.Command, _ []string) error {
88-
return download.HasUpdate(dir)
89-
},
90-
}
91-
9265
func downloadCLI() *cobra.Command {
9366
downloadCmd = addDataDir(downloadCmd)
9467
downloadCmd.Flags().BoolVarP(&skipExistingFiles, "skip", "x", false, "skip the download of existing files")
@@ -97,7 +70,6 @@ func downloadCLI() *cobra.Command {
9770
downloadCmd.Flags().IntVarP(&parallelDownloads, "parallel", "p", download.DefaultMaxParallel, "maximum parallel downloads")
9871
downloadCmd.Flags().Int64VarP(&chunkSize, "chunk-size", "c", download.DefaultChunkSize, "max length of the bytes range for each HTTP request")
9972
downloadCmd.Flags().BoolVarP(&restart, "restart", "e", false, "restart all downloads from the beginning")
100-
downloadCmd.Flags().StringVarP(&useMirror, "mirror", "m", "", "download from the mirror, not from the original source (YYYY-MM-DD)")
10173
return downloadCmd
10274
}
10375

@@ -106,12 +78,3 @@ func urlsCLI() *cobra.Command {
10678
urlsCmd.Flags().BoolVarP(&skipExistingFiles, "skip", "x", false, "skip the download of existing files")
10779
return urlsCmd
10880
}
109-
110-
func updatedAtCLI() *cobra.Command {
111-
return updatedAtCmd
112-
}
113-
114-
func hasUpdateCLI() *cobra.Command {
115-
hasUpdateCmd = addDataDir(hasUpdateCmd)
116-
return hasUpdateCmd
117-
}

docs/servidor.md

+5-14
Original file line numberDiff line numberDiff line change
@@ -17,16 +17,7 @@ Usando MongoDB, a URI será `mongodb://minhareceita:minhareceita@loocalhost:2701
1717

1818
## Download dos dados
1919

20-
O comando `download` baixa dados da Receita Federal, mais um arquivo do Tesouro Nacional com o código dos municípios do IBGE.
21-
22-
*Atenção*, por enquanto é preciso baixar manualmente os 4 arquivos de regime tributário:
23-
24-
1. Acessar [dados.gov.br](https://dados.gov.br)
25-
2. Buscar por CNPJ
26-
3. Acessar o recurso _Regime Tributário_
27-
4. Baixar os quatro arquivos terminados em `.zip`
28-
29-
O servidor da Receita Federal é lento e instável, então todo os arquivos são [baixados em pequenas fatias](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range).
20+
O comando `download` baixa dados da Receita Federal, mais um arquivo do Tesouro Nacional com o código dos municípios do IBGE. O servidor da Receita Federal pode ser lento e instável, então todo os arquivos são [baixados em pequenas fatias](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range).
3021

3122
O comando aceita um opção `--directory` (ou `-d`) com um diretório onde serão salvos os arquivos originais da Receita Federal. O padrão é `data/`.
3223

@@ -37,20 +28,20 @@ Caso o download falhe, é recomendado variar as configurações explicadas no `-
3728
* tempo limite para cada fatia com `--timeout` (ou `-t`)
3829
* rodar o comando de download sucessivas vezes com a opção `--skip` (ou `-x`) para baixar apenas os arquivos que estão faltando
3930

40-
Em último caso, é possível listar as URLs para download dos arquivos com comando `urls`; e, então, tentar fazer o download de outra forma (manualmente, com alguma ferramenta que permite recomeçar downloads interrompidos, etc.).
31+
Em último caso, é possível listar as URLs para download dos arquivos com comando `urls`; e, então, tentar fazer o download de outra forma (manualmente, com alguma ferramenta que permite recomeçar downloads interrompidos, etc.). Caso essa seja uma opção crie um arquivo `updated_at.txt` no mesmo diretório com a data de extração dos dados no formato `YYYY-MM-DD`.
4132

4233
### Espelho dos dados
4334

44-
O _Minha Receita_ mantém um [espelho dos dados em uma diretório compartilhado](https://mirror.minhareceita.org). Você pode fazer o download dos arquivos de lá (ao invés de utilizar o servidor oficial) com a opção `--mirror YYYY-MM-DD` substituindo a data por alguma das disponíveis no espelho.
35+
O _Minha Receita_ mantém um [espelho dos dados em uma diretório compartilhado](https://mirror.minhareceita.org).
4536

4637
### Exemplos de uso
4738

4839
Sem Docker:
4940

5041
```console
51-
$ minha-receita download --urls-only
42+
$ minha-receita download
5243
$ minha-receita download --timeout 1h42m12s
53-
$ minha-receita download --mirror 2022-12-17
44+
$ minha-receita urls
5445
```
5546

5647
Com Docker:

download/download.go

+4-44
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@ func getURLs(url string, handler getURLsHandler, dir string, skip bool) ([]strin
2121
if !skip {
2222
return urls, nil
2323
}
24-
2524
var out []string
2625
for _, u := range urls {
2726
p := filepath.Join(dir, filepath.Base(u))
@@ -66,39 +65,22 @@ func Download(dir string, timeout time.Duration, skip, restart bool, parallel in
6665
if err != nil {
6766
return fmt.Errorf("error gathering resources for download: %w", err)
6867
}
69-
tr, err := getURLs(taxRegimeURL, taxRegimeGetURLs, dir, skip)
70-
if err != nil {
71-
return fmt.Errorf("error gathering resources for download: %w", err)
72-
}
73-
urls = append(urls, tr...)
7468
if len(urls) == 0 {
7569
return nil
7670
}
7771
if err := download(dir, urls, parallel, retries, chunkSize, timeout, restart); err != nil {
7872
return fmt.Errorf("error downloading files from the federal revenue: %w", err)
7973
}
80-
if err := federalRevenueGetMetadata(federalRevenueMetadataURL, dir); err != nil {
81-
return fmt.Errorf("error getting metadata: %w", err)
82-
}
83-
return nil
84-
}
85-
86-
// Download all the files from the project's mirror
87-
func DownloadFromMirror(mirror string, dir string, timeout time.Duration, skip, restart bool, parallel int, retries uint, chunkSize int64) error {
88-
urls, err := getMirrorURLs(mirror)
89-
if err != nil {
90-
return fmt.Errorf("error getting mirror urls: %w", err)
91-
}
92-
if err := download(dir, urls, parallel, retries, chunkSize, timeout, restart); err != nil {
93-
return fmt.Errorf("error downloading files from the mirror: %w", err)
74+
if err := saveUpdatedAt(dir); err != nil {
75+
return fmt.Errorf("error getting updated at date: %w", err)
9476
}
9577
return nil
9678
}
9779

9880
// URLs shows the URLs to be downloaded.
9981
func URLs(dir string, skip bool) error {
100-
urls := []string{federalRevenueURL, nationalTreasureBaseURL, taxRegimeURL}
101-
handlers := []getURLsHandler{federalRevenueGetURLs, nationalTreasureGetURLs, taxRegimeGetURLs}
82+
urls := []string{federalRevenueURL, nationalTreasureBaseURL}
83+
handlers := []getURLsHandler{federalRevenueGetURLs, nationalTreasureGetURLs}
10284
var out []string
10385
for idx := range urls {
10486
u, err := getURLs(urls[idx], handlers[idx], dir, skip)
@@ -111,25 +93,3 @@ func URLs(dir string, skip bool) error {
11193
fmt.Println(strings.Join(out, "\n"))
11294
return nil
11395
}
114-
115-
// UpdatedAt shows the updated at of the files to be downloaded.
116-
func UpdatedAt() error {
117-
u, err := fetchUpdatedAt(federalRevenueMetadataURL)
118-
if err != nil {
119-
return fmt.Errorf("error getting updated at: %w", err)
120-
}
121-
fmt.Println(u)
122-
return nil
123-
}
124-
125-
// HasUpdate checks if there is an update available.
126-
func HasUpdate(dir string) error {
127-
h, err := hasUpdate(federalRevenueMetadataURL, dir)
128-
if err != nil {
129-
return fmt.Errorf("error getting updated at: %w", err)
130-
}
131-
if !h {
132-
os.Exit(1)
133-
}
134-
return nil
135-
}

download/download_test.go

+2-1
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,8 @@ func TestGetURLs(t *testing.T) {
1717
handler getURLsHandler
1818
expected int
1919
}{
20-
{"federal revenue", []string{"dados_abertos_cnpj.html", "2024-08.html"}, federalRevenueGetURLs, 37},
20+
{"federal revenue", []string{"dados_abertos_cnpj.html", "2024-08.html", "regime_tributario.html"}, federalRevenueGetURLs, 41},
21+
2122
{"national treasure", []string{"national-treasure.json"}, nationalTreasureGetURLs, 1},
2223
} {
2324
ts := httpTestServer(t, tc.fixture)

download/downloader_test.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,10 @@ import (
88
)
99

1010
func TestDownloader(t *testing.T) {
11-
ts := httpTestServer(t, []string{"cadastro-nacional-de-pessoa-juridica-cnpj.json"})
11+
ts := httpTestServer(t, []string{"Empresas1.zip"})
1212
defer ts.Close()
1313

14-
f, s := loadFixture(t, "cadastro-nacional-de-pessoa-juridica-cnpj.json")
14+
f, s := loadFixture(t, "Empresas1.zip")
1515
defer f.Close()
1616

1717
tmp := t.TempDir()

0 commit comments

Comments
 (0)