Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[BACKPORT] Write a doc example on multi-language Mill projects #4494

Merged
merged 3 commits into from
Feb 6, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions docs/modules/ROOT/nav.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -102,14 +102,14 @@
** xref:extending/meta-build.adoc[]
** xref:extending/example-typescript-support.adoc[]
** xref:extending/example-python-support.adoc[]
* xref:large/large.adoc[]
** xref:large/selective-execution.adoc[]
** xref:large/multi-file-builds.adoc[]
** xref:large/multi-language-builds.adoc[]
// This section focuses on diving into deeper, more advanced topics for Mill.
// These are things that most Mill developers would not encounter day to day,
// but people developing Mill plugins or working on particularly large or
// sophisticated Mill builds will need to understand.
* xref:large/large.adoc[]
** xref:large/selective-execution.adoc[]
** xref:large/multi-file-builds.adoc[]

* Mill In Depth
** xref:depth/sandboxing.adoc[]
** xref:depth/execution-model.adoc[]
Expand Down
4 changes: 4 additions & 0 deletions docs/modules/ROOT/pages/large/multi-language-builds.adoc
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
= Multi-Language Builds
:page-aliases: Multi_Language_Builds.adoc

include::partial$example/large/multi/14-multi-language.adoc[]
76 changes: 76 additions & 0 deletions example/large/multi/14-multi-language/build.mill
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
package build
import mill._, javascriptlib._, pythonlib._, javalib._

object client extends ReactScriptsModule

object `sentiment-analysis` extends PythonModule {
def mainScript = Task.Source { millSourcePath / "src" / "foo.py" }

def pythonDeps = Seq("textblob==0.19.0")

object test extends PythonTests with pythonlib.TestModule.Unittest
}

object server extends JavaModule {
def ivyDeps = Agg(
ivy"org.springframework.boot:spring-boot-starter-web:2.5.6",
ivy"org.springframework.boot:spring-boot-starter-actuator:2.5.6"
)

/** Bundle client & sentiment-analysis as resource */
def resources = Task.Sources {
os.copy(client.bundle().path, Task.dest / "static")
os.makeDir.all(Task.dest / "analysis")
os.copy(`sentiment-analysis`.bundle().path, Task.dest / "analysis" / "analysis.pex")
super.resources() ++ Seq(PathRef(Task.dest))
}

object test extends JavaTests with javalib.TestModule.Junit5 {
def ivyDeps = super.ivyDeps() ++ Agg(
ivy"org.springframework.boot:spring-boot-starter-test:2.5.6"
)
}
}

// This example demonstrates a simple multi-langauge project,
// running a `spring boot webserver` serving a `react client` and interacting with a `python binary`
// through the web-server api.

/** Usage

> mill client.test
PASS src/test/App.test.tsx
...Text Analysis Tool
...renders the app with initial UI...
...displays sentiment result...
...
Test Suites:...1 passed, 1 total
Tests:...2 passed, 2 total
...

> mill sentiment-analysis.test
...
test_negative_sentiment... ok
test_neutral_sentiment... ok
test_positive_sentiment... ok
...
Ran 3 tests...
...
OK
...

> mill server.test
...com.example.ServerTest#shouldReturnStaticPage() finished...
...com.example.ServerTest#shouldReturnPositiveAnalysis() finished...
...com.example.ServerTest#shouldReturnNegativeAnalysis() finished...

> mill server.runBackground

> curl http://localhost:8086
...<title>Sentiment Analysis Tool</title>...

> curl -X POST http://localhost:8086/api/analysis -H "Content-Type: text/plain" --data "This is awesome!" # Make request to the analysis api
Positive sentiment (polarity: 1.0)

> mill clean server.runBackground
*/
43 changes: 43 additions & 0 deletions example/large/multi/14-multi-language/client/public/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.

Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>Sentiment Analysis Tool</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.

You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.

To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
90 changes: 90 additions & 0 deletions example/large/multi/14-multi-language/client/src/App.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Arial', sans-serif;
}

body {
background: #f4f4f4;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}

.app-container {
background: #fff;
border-radius: 12px;
padding: 40px;
width: 400px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
text-align: center;
}

h1 {
margin-bottom: 20px;
font-size: 1.8rem;
color: #333;
}

.analysis-form {
display: flex;
flex-direction: column;
gap: 10px;
}

textarea {
width: 100%;
height: 120px;
padding: 10px;
font-size: 1rem;
border: 1px solid #ccc;
border-radius: 8px;
resize: none;
outline: none;
}

textarea:focus {
border-color: #007bff;
}

button {
padding: 10px;
background: #007bff;
color: #fff;
border: none;
border-radius: 8px;
cursor: pointer;
font-size: 1rem;
}

button:hover {
background: #0056b3;
}

button:disabled {
background: #b0c4de;
cursor: not-allowed;
}

.result-container {
margin-top: 20px;
padding: 15px;
border-radius: 8px;
color: #fff;
font-weight: bold;
}

/* Sentiment-based styles */
.result-container.positive {
background-color: #28a745; /* Green for positive */
}

.result-container.negative {
background-color: #dc3545; /* Red for negative */
}

.result-container.neutral {
background-color: #007bff; /* Blue for neutral */
}
76 changes: 76 additions & 0 deletions example/large/multi/14-multi-language/client/src/app/App.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import React, {useState} from 'react';
import 'src/App.css';

const App = () => {
const [inputText, setInputText] = useState('');
const [result, setResult] = useState('');
const [loading, setLoading] = useState(false);
const [sentiment, setSentiment] = useState('neutral');

const handleSubmit = async (e) => {
e.preventDefault();
setLoading(true);
setResult('');
setSentiment('neutral');

try {
const response = await fetch('http://localhost:8086/api/analysis', {
method: 'POST',
headers: {
'Content-Type': 'text/plain',
},
body: inputText,
});

if (response.ok) {
const responseData = await response.text();
setResult(responseData);

// Determine sentiment from the response
const polarityMatch = responseData.match(/polarity: ([+-]?[0-9]*\.?[0-9]+)/);
if (polarityMatch) {
const polarity = parseFloat(polarityMatch[1]);

if (polarity > 0) {
setSentiment('positive');
} else if (polarity < 0) {
setSentiment('negative');
} else {
setSentiment('neutral');
}
}
} else {
setResult('Error occurred during analysis.');
}
} catch (error) {
setResult('Network error: Could not connect to the server.');
} finally {
setLoading(false);
}
};

return (
<div className="app-container">
<h1>Text Analysis Tool</h1>
<form onSubmit={handleSubmit} className="analysis-form">
<textarea
value={inputText}
onChange={(e) => setInputText(e.target.value)}
placeholder="Enter your text here..."
required
/>
<button type="submit" disabled={loading}>
{loading ? 'Analyzing...' : 'Analyze'}
</button>
</form>
{result && (
<div className={`result-container ${sentiment}`}>
<h2>Analysis Result:</h2>
<p>{result}</p>
</div>
)}
</div>
);
};

export default App;
12 changes: 12 additions & 0 deletions example/large/multi/14-multi-language/client/src/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './app/App';

const root = ReactDOM.createRoot(
document.getElementById('root') as HTMLElement
);
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
47 changes: 47 additions & 0 deletions example/large/multi/14-multi-language/client/src/test/App.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import React from 'react';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import '@testing-library/jest-dom'; // Import jest-dom matchers
import App from 'app/App';

// Mock the fetch API
global.fetch = jest.fn();

describe('Text Analysis Tool', () => {
beforeEach(() => {
(fetch as jest.Mock).mockClear();
});

test('renders the app with initial UI', () => {
render(<App />);

// Check for the page title
expect(screen.getByText('Text Analysis Tool')).toBeInTheDocument();

// Check for the input form
expect(screen.getByPlaceholderText('Enter your text here...')).toBeInTheDocument();
expect(screen.getByText('Analyze')).toBeInTheDocument();
});

test('displays sentiment result', async () => {
// Mock the fetch response for positive sentiment
(fetch as jest.Mock).mockResolvedValueOnce({
ok: true,
text: async () => 'Positive sentiment (polarity: 0.8)',
});

render(<App />);

// Simulate user input and form submission
fireEvent.change(screen.getByPlaceholderText('Enter your text here...'), {
target: { value: 'This is amazing!' },
});
fireEvent.click(screen.getByText('Analyze'));

// Wait for the result to appear
await waitFor(() => screen.getByText('Analysis Result:'));

// Check that the result is displayed
expect(screen.getByText('Positive sentiment (polarity: 0.8)')).toBeInTheDocument();
expect(screen.getByText('Analysis Result:').parentElement).toHaveClass('positive');
});
});
Loading
Loading